Moving a sprite around the circumference of a circle in Cocos2d-iPhone

一笑奈何 提交于 2019-12-21 03:00:55

问题


I am new to Cocos2d. I have taken a look at the documentation at it looks pretty simple compared to what you need to do using basic Iphone classes such as UIAnimation etc.

I want to move a Sprite (eg. Bird, Plane or Car) around the center of a circle around its circumference, smoothly so that even the sprite rotates accordingly.

How is this possible in Cocos2d? It would be very helpful if someone can post some basic code.

Thanks.


回答1:


One way to do it is to schedule a selector to run periodically, and when it's called, move your sprite over the circle.

To do that, you can take a look at the functions at CGPointExtension.m. In particular, you can use ccpForAngle, ccpMult, and ccpAdd. You could do something like this:

// Assume the class is a subclass of CCNode, and has the following properties:
// radius: the radius of the circle you want the sprite to move over.
// circleCenter: the center of the circle
// currentAngle: the angle where the sprite currently is
- (void)tick {
    float anglePerTick = 0.1; // this will determine your speed
    currentAngle += anglePerTick;  
    self.position = ccpAdd(ccpMult(ccpForAngle(currentAngle), radius)),
                           circleCenter);
    self.rotation = currentAngle * 180 / M_PI; // Convert from radians to degrees
}

The main problem with this approach is that you are setting the angular velociy as a constant, so if the circle gets bigger, the "distance" the sprite will travel on each tick will increase, and may lead to flickering.



来源:https://stackoverflow.com/questions/2786812/moving-a-sprite-around-the-circumference-of-a-circle-in-cocos2d-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!