Converting position with regarding anchorPoint?

330 Views Asked by At

I have a sprite, which is added to CCSpriteBatchNode. Then I fix position of the sprite, changing anchor point the way so I can rotate sprite around that point.

Hierarchy is sprite <- batchNode <- scene

Basically sprite is moving but it's .position property is not changing. I need to get the real position of the sprite after transformations. So I tried to use

CGPoint p = sprite.position;
p = [sprite convertToWorldSpace:p];

However, position is not matching to the sprite's position which I see in the scene.

1

There are 1 best solutions below

6
Abhineet Prasad On

Sprite position is a point at the middle of the CCSprite(by default). Changing the anchor point moves the sprite such that the point moves with respect to the sprite but remains same with respect to the world space. For example, changing the anchor point of a sprite(say square) to ccp(0,0) will move the square so that its bottom left vertex will come at the position where the square's center point was initially. So while the square may seem to be "repositioned" ,its position (property) stays the same(unaffected by change in anchor point) unless specifically changed.

EDIT

If by real position of the sprite, you mean its mid point after its anchor point has been changed then it can be calculated by taking into account the two transformations that have been applied on it i.e. Translation and Rotation.

First we take care of Translation:

Your sprite has moved by:

CGPoint translation;
translation.x =  sprite.contentSize.width x (0.5 - sprite.anchorPoint.x);
translation.y =  sprite.contentSize.height x (0.5 - sprite.anchorPoint.y);    

Now we accomodate for change in Rotation

Converting "translation" point into polar coordinates we get

#define RADIANS_TO_DEGREES(radians) ((radians) * (180.0 / M_PI))
r = ccpDistance(translation,ccp(0,0));
ø = RADIANS_TO_DEGREES(atan2(translation.x,translation.y)); //i take x/y here as i want the CW angle from y axis.

If you rotated your sprite by "D" degrees:

 ø = ø + D;
 CGPoint transPositionAfterRotation = ccp(r * cos(ø),r * sin(ø) );

CGPoint realPosition =  ccp(sprite.position.x + transPositionAfterRotation.x, sprite.position.y +transPositionAfterRotation.y)