我已经四处寻找了一段时间,但出于某种原因我一直没能找到答案。看起来很简单,但也许我只是在库中找不到合适的函数。
我有一个场景,其中有一个层包含一堆 CCNode,每个 CCNode 中都有一个 CCSprite。
在应用程序期间,我在主层的位置周围移动,以便以某种方式在相机周围“平移”。 (即我平移整个图层,以便视口(viewport)发生变化)。
现在我想确定 CCNode 在屏幕坐标中的绝对位置。 position 属性返回相对于父节点的位置,但我真的希望将其转换为它在屏幕上的实际位置。
此外,作为额外的奖励,如果我可以将此位置表示为坐标系,其中 0,0 映射到屏幕的左上角,1,1 映射到屏幕的右下角,那就太棒了。 (所以我与所有设备保持兼容)
编辑:请注意,该解决方案最好适用于任何 CCNode 层次结构。
最佳答案
每个 CCNode 及其后代都有一个名为 convertToWorldSpace:(CGPoint)p 的方法
这将返回相对于场景的坐标。
有了这个坐标后,翻转 Y 轴,因为您希望 0,0 位于左上角。
CCNode * myNode = [[CCNode alloc] init];
myNode.position = CGPointMake(150.0f, 100.0f);
CCSprite * mySprite = [[CCSprite alloc] init]; // CCSprite is a descendant of CCNode
[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 convertToWorldSpace: mySprite.position];
// to convert it to Y0 = top we should take the Y of the screen, and subtract the worldCoord Y
worldCoord = CGPointMake(worldCoord.x, ((CGSize)[[CCDirector sharedDirector] displaySizeInPixels]).height - worldCoord.y);
// This is dry coded so may contain an error here or there.
// Let me know if this doesn't work.
[mySprite release];
[myNode release];
关于iphone - Cocos2D CCNode 在绝对屏幕坐标中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5766522/