1
votes

I am developing a iphone application using cocos2d and i have a problem with converting the coordinates from parent to child space.

I have N elements where each element has a position (0,0 is in the top left corner and not in bottom left) and each element can have a parent. And if the element has a parent its position is in the local coordinate space of the parent.

Example:

Sprite1 at global position(10,10)
Sprite2 at global position(20,20)
   Sprite3 at local position(20,20) and at global position(40,40)
      Sprite4 at local position(30,30) and at global position(70,70) 

When i add a sprite i compute the coordinate like this (without a parent):

CCSprite * sprite = [CCSprite spriteWithFile:image];
CGPoint position =  [[CCDirector sharedDirector] convertToGL: ccp(element.x, element.y);
sprite.position = position;

and since the elements coordinate space starts in the top left corner i have to set the anchor point:

sprite.anchor = ccp(0,1)

This works for elements without a parent, but when i add a element with a parent (with the above code) the positions are wrong. How can i correctly calculate the coordinates (without having to iterate through all parents)?

Thanks.

1

1 Answers

0
votes

CCNode has the methods the convertFromWorldSpace(AR): and convertToWorldSpace(AR):. You can use them to first convert to world coordinates and then back to the parent's space.