giripp
giripp

Reputation: 385

Bézier Curve Didn't Draw Straight

I did make algorithm for creating Bézier Curve with Objective-C and Cocos2D. Here is my code

-(int)factorial:(int)x{
    int sum=1;
    int i;
    if(x == 0){
        return 1;
    }else{
        for(i=1;i<x;i++){
            sum = sum*i;
        }
        return sum;
        }
}

-(int)binomialCoefficient:(int)n:(int)i{
    int sum;
    //NSLog([NSString stringWithFormat:@"fac n-i=%f\n", fach] );
    sum = [self factorial:n]/([self factorial:i]*[self factorial:(n-i)]);

    return sum;
}

-(float)convertT:(int)t{
    return t*(0.001);
}

-(float)power:(float)a:(int)b{
        int i;
    float hasil=1;
    for(i=0;i<b;i++){
        hasil = hasil*a;
    }
    return hasil;
}

-(float)bernstein:(float)t:(int)n:(int)i{
    float sum = 0;

    sum = [self binomialCoefficient:n:i]*[self power:t :i]*[self power:(1-t) :(n-i)];
    //NSLog([NSString   stringWithFormat:@"yeah"]);
    return sum;
}

and for implementation you just put an array of x and y and access it. For example to draw a single dot in control curve I did it like this

float myPx = px[i];
float myPy = py[i];
posx = posx+([self bernstein:theT :banyak-1 :i]*myPx);
posy = posy+([self bernstein:theT :banyak-1 :i]*myPy);

Yes, this code doesn't give the perfect nice line, but I try to draw it dot by dot. It works well, but the problem arise when I try to use 3 dots. The middle dot for curving the lines didn't behave like what I expected. For example if I put 3 dots in these coordinates: a(100,200) b(250,250) c(500,200)

It didn't curving up but curving down. If I want to put it straight I have to put it all the way higher.

Am I do it wrong in syntax or data types? Or is it just my algorithm?

Thanks in advance

Best Regards (sorry for my bad english)

Upvotes: 0

Views: 353

Answers (1)

Cyrille
Cyrille

Reputation: 25144

The factorial loop should be

for ( i = 1 ; i <= x ; i++ )

instead of

for ( i = 1 ; i < x ; i++ )

Upvotes: 1

Related Questions