stone
stone

Reputation: 841

cocos2d convertToWorldSpace

I'm not sure convertToWorldSpace works.

Upvotes: 6

Views: 10368

Answers (2)

Stan Tatarnykov
Stan Tatarnykov

Reputation: 699

ConvertToWorldSpace takes LOCAL node coordinates, and converts them to the world coordinates. ConvertToNodeSpace takes WORLD coordinates, converts them to the calling node's coordinates. (If so call [nodeA convertToWorldSpace:ccp(10,10)], it assumes that the (10,10) position is for a child of nodeA)

Basically, To get the world position of any node (in cocos2d 3 or later) use this code:

CGPoint worldPosition=[node.parent convertToWorldSpace:node.positionInPoints];

I personally made a function so I can use this over and over (add it to the top of any .m/.h file and you will see it)

static inline CGPoint
worldPosOfNode(CCNode *node){
    return [node.parent convertToWorldSpace:node.positionInPoints];
}

And I use it like this: (myNode can be any cocos2d sprite, label or whatever)

CGPoint worldPosition=worldPosOfNode(myNode);

Upvotes: 2

Yannick Loriot
Yannick Loriot

Reputation: 7136

In your case if you want know the position of your spriteB in the current world you must call the "convertToWorldSpace" methods from its parent (the spriteA) :

[spriteA convertToWorldSpace:spriteB.position];

The "convertToWorldSpace:" method applies the node's transformation to the given position. You should always call this methods from the parent's sprite.

Upvotes: 12

Related Questions