Rotating a sprite on a Bezier curve in cocos2d

I am trying to make a sprite follow a bezier curve. I found a few forum posts over on the cocos2d site and followed the directions but i still dont seem to be able to get the sprite to rotate correctly. Can anyone help.

The code i have added into the update method of the BezierBy function is as follows

float qx = (powf(1-t,2)*xa + 2*(1-t)*t*xb+powf(t,2)*xc);
float qy = (powf(1-t,2)*ya + 2*(1-t)*t*yb+powf(t,2)*yc);

double deltaX = x-qx;
double deltaY = y-qy;

double degrees = (-180/M_PI)*ccpToAngle(CGPointMake(deltaX,deltaY));

[target_ setRotation:degrees];

The original article can be found here

Any help would be great at the moment the rotation seems quite erratic

Upvotes: 3

Views: 2962

Answers (2)

RajivSK
RajivSK

Reputation: 41

I would suggest you calculate the angle of the sprites movement during the last frame and use this value to rotate the sprite accordingly. This method will work for every type of movement including complicated bezier paths. This will also save you the work of timing the rotation to the movement compared to the other solution offered.

CGPoint vector = ccpSub(sprite.position, lastPosition);
sprite.rotation = atan2(vector.x, vector.y) * 180 / M_PI;
lastPosition = sprite.position;

You will of course need to put this code in an update loop with lastPosition as a global variable.

Upvotes: 4

Nikhil Aneja
Nikhil Aneja

Reputation: 1259

Whenever I need a sprite to follow on a particular Bezier path and rotate accordingly. I create a bezier path using CCBezier. And use CCRotateTo method for rotating the sprite to a particular angle. The duration of rotation is duration of bezierAction and angle of rotation can be calculated manually. Like in your pic angle is from -45 to 45. So code might look like this..

ccBezierConfig bezier;
bezier.controlPoint_1 = ccp(0, s.height/2);
bezier.controlPoint_2 = ccp(300, -s.height/2);
bezier.endPosition = ccp(300,100);

id bezierForward = [CCBezierBy actionWithDuration:10 bezier:bezier];
[sprite runAction:bezierForward];

[sprite setRotation:-45];
[sprite runAction:[CCRotateTo actionWithDuration:10 angle:45]];

Fill values accordingly.. This is just a snippet code.. :)

Upvotes: 4

Related Questions