cocos2d convertToWorldSpace

大憨熊 提交于 2020-01-10 15:41:13

问题


I'm not sure convertToWorldSpace works.

  • I have spriteA which is the parent.

  • I set it to position 40,40 for example and add it to the scene.

  • I have a second spriteB which I set at position 80,80.

  • I add spriteB to spriteA.

  • I print out the position of spriteB: 80,80.

  • I then print [self convertToWorldSpace:spriteB.position]. And, I still get 80,80. Shouldn't spriteB position be different here?


回答1:


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.




回答2:


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);


来源:https://stackoverflow.com/questions/5045115/cocos2d-converttoworldspace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!