0
votes

Is there any cocos2d function that returns the parent coordinate given a node local coordinate? It must be quite a common use case, but I've not found any native cocos2d function. Is there any?

I guess it's something like this. NOTE, I haven't tested this one. ;)

-(CGPoint) nodeToParent: (CGPoint) localPoint
{
  CGFloat phi = -self.rotation * B2_pi / 180;
  return ccpAdd(self.position, ccpRotateByAngle(localPoint, ccp(0, 0), phi));
}
4

4 Answers

3
votes

As m.ding said ... parent->ConvertToNodeSpace() .....

Here's explanation for you so you know when to do what ?

convertToWorldSpace(const CCPoint& nodePoint) converts on-node coords to SCREEN coordinates. Lets we have layerA with anchor point and position (0,0) attached to screen and have a sprite on this layer at point (100, 100). What will be SCREEN coords of sprite? - (100, 100)

Lets we moved layerA to point (- 50, - 20). What will be SCREEN coords of sprite? - (100 - 50, 100 - 20), i.e. (50, 80) - that's what convertToWorldSpace returns to us if we call layerA->convertToWorldSpace(ccp(100, 100)).

As for convertToWorldSpaceAR - will return the position relatevely to anchor point: so if our scene - root layer has AP (0.5f, 0.5f) - default, convertToWorldSpaceAR should return position relatively to screen center. I have used convertToNodeSpace

convertToNodeSpace(const CCPoint& worldPoint) - converts SCREEN coords to NODE's local. I.e. if for our example with moved layer call: layerA->convertToNodeSpace(ccp(50, 80)) - that should return (100, 100) - our sprite on-node coords.

convertToNodeSpaceAR - the same logic as for convertToWorldSpaceAR

1
votes

assume your parent node is

CCSprite* parent;

you can use:

parent->convertToNodeSpace();
0
votes

I guess that

-(CGPoint) convertToWorldSpace:(CGPoint)pt

could do the trick, take a look here.

0
votes

It looks like you are on the right track. [node position] should give the position of the node in the parent's coordinate space, so if you have a local point that is offset from the [node position] then you need to do add the offset like you have done. I'm not sure the ccpRotateByAngle is the right method to do that but you'll just have to test it and find out!