gdbj
gdbj

Reputation: 17485

Trouble with Translate CCNode using convertToWorldSpaceAR

I'm a bit confused by the behaviour of my Cocos2d instance, and I need some help. I borrowed this code from Cocos2D CCNode position in absolute screen coordinates. Pretty simple: two objects, one a child of the other.

Running the below code snippet, I am getting worldCoord = (50, 200). My expectation would be that the translation would result in worldCoord = (100, 150). When I step through the code, tx = 100, and ty = 150 in the CGAffineTransform. Why?

CCNode * myNode = [[CCNode alloc] init];
[myNode setAnchorPoint:CGPointZero];
myNode.position = CGPointMake(150.0f, 100.0f);

CCNode * mySprite = [[CCNode alloc] init]; // CCSprite is a descendant of CCNode
[mySprite setAnchorPoint:CGPointZero];
[myNode addChild: mySprite];
mySprite.position = CGPointMake(-50.0f, 50.0f);

// we now have a node with a sprite in in. On this sprite (well, maybe
// it you should attack the node to a scene) you can call convertToWorldSpace:
CGPoint worldCoord = [mySprite convertToWorldSpaceAR: mySprite.position];

Upvotes: 1

Views: 319

Answers (1)

CodeSmile
CodeSmile

Reputation: 64477

Considering that mySprite is a child of myNode and thus offset by the myNode position:

myNode.position = CGPointMake(150.0f, 100.0f);
mySprite.position = CGPointMake(-50.0f, 50.0f);

Then you are correct to assume that mySprite's world pos should be:

X: (150 + -50) = 100
Y: (100 +  50) = 150

To get the sprite's world position use the non-AR variant of convertToWorldSpace:

CGPoint worldCoord = [myNode convertToWorldSpace: mySprite.position];

Note that you need to convert using the parent node, as it defines the coordinate space for its children. In other words a child node's origin (0,0) is equivalent to the position of its parent.

This variant of the method will also not be affected by changes in the sprite's anchorPoint. Only the 'AR' variant's results will change when you change the sprite anchor point.

The 'AR' variant simply adds the node's anchorPoint to the position before converting it. Assuming your sprite's contentSize is 100x100 and the anchorPoint is at the default 0.5,0.5 then 50,50 is added to mySprite.position before being converted to world space. In other words it adds the offset between the sprite texture's lower left corner to the sprite's position to the converted position.

Upvotes: 1

Related Questions