Rotating a sprite on a Bezier curve in cocos2d

I am trying to make a sprite following a Bezier curve. I found several forum posts on the cocos2d site and followed the directions, but I still can't get the sprite to rotate correctly. Can anyone help.

The code added to the BezierBy function update method 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 a point where the rotation seems to be quite erratic

+3


source to share


2 answers


Whenever I need a sprite to follow a specific Bezier path and rotate accordingly. I am creating a bezier path using CCBezier

. And use the CCRotateTo method to rotate the sprite by a specific angle. The rotation duration is the bezier duration and the rotation angle can be calculated manually. As in your corner with a picture from -45 to 45. So the 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 in the values ​​accordingly. This is just a snippet code .. :)

+4


source


I would suggest that you calculate the angle of movement of the sprites during the last frame and use that value to rotate the sprite accordingly. This method will work for every type of motion, including complex bezier paths. It will also save you the time it takes to rotate the movement compared to the other proposed solution.

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

      



Of course, you need to put this code in your update loop with lastPosition

as a global variable.

+4


source







All Articles