views:

556

answers:

1

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.

A: 

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.

pgb
I subclassed CCSprite and did as you said and call tick periodically, the sprite moves around the radius, but it does not rotate accordingly, Am i missing something?
CircleOfLife
You can change the rotation property. I just updated the code to reflect it.
pgb
I tried this, but the rotation happens very slowly, not according to the movement speed. I will add my code, so please tell me what I am doing wrong
CircleOfLife
@pgb : Please can you tell me where I am going wrong, I have added the code as an answer.
CircleOfLife
The rotation property is in degrees and not in radians, so you need to convert it. I have updated my code sample to read `self.rotation = currentAngle * 180 / M_PI;`. By the way, you should update your question instead of posting an additional answer, so it's less confusing to visitors that find your question on the site.
pgb
Thanks a lot, you have to multiply the self.rotation with -1 to make it move properly I noticed. Another thing is that it flickers quite a lot, is there a way to remove this flickering?
CircleOfLife
I think the flickering is because `anglePerTick` is to high, and the interval you use to call it may be to high as well. You may try with an `anglePerTick` of 0.05 and calling the method at 30 or 60 fps, to see if it flickers a bit less.
pgb