Getting absolute position of CCSprite in cocos2d

↘锁芯ラ 提交于 2019-12-21 05:27:07

问题


In my game, I have a CCSprite that orbits another CCSprite, much like an electron orbiting a nucleus. I have the electron as a child of the nucleus, to make animation much simpler. All I have to do is rotate the nucleus and the electron follows suite quite nicely.

However, my problem comes from wanting to have the orbit animation appear a little snazzier, by either adding something like a particle system trail, or a ribbon effect following the path of the electron. I cannot simply add a particle system to the electron itself, because the particles don't follow correctly, since they are being rotated by the nucleus as well. If I add the particle system to self, then they appear correctly, but not in the same position as the object they are supposed to be trailing.

My question is this:

Is there a way to get the scene position of an object, say the electron, as opposed to only having access to it's position relative to it's parent?

Thanks.


回答1:


Yes there is!

Each CCNode and its descendants has the ability to get a position relative to the scene:

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

This worldCoordinate will be relative to the scene as opposed to the parent node!

Hope this helped! ^_^




回答2:


A later edit:

When you do:

[aSprite convertToWorldSpace:position];

You are actually getting the global coordinates of position in aSprite's coordinate system. If you want to translate aSprite's position to global space you need to ask for it's parent to do the translation for you, because the sprite.position is already in it's parents coordinates system.

Hope it explains it


Original Answer:

For me this solution did not work

I had a 2 level hierarchy where mySprite is a child of a CCSprite that is a child of the scene.

Bottom line: This code fixed the problem for me:

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

This is the hierarchy structure that required my solution: myScene -> mySpriteParent -> mySprite

mySprite.position:29,254
mySpriteParent.position:533,57

Solution1 - wrong result:

[mySprite convertToWorldSpace: mySprite.position]:91,418

Solution2 - right result:

[[boxSprite parent] convertToWorldSpace:boxSprite.position]:253.5,275.5

Perhaps this solution will help someone And maybe someone will explain why this solution works and not the other



来源:https://stackoverflow.com/questions/10215869/getting-absolute-position-of-ccsprite-in-cocos2d

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