问题描述
我已经四处寻找了一段时间,但由于某种原因我无法找到答案.看起来很简单,但也许我只是在库中找不到合适的函数.
I've been looking around for a while, and I have not been able to find an answer to this for some reason. It seems simple enough, but maybe I just can't find the right function in the library.
我有一个包含一堆 CCNode 的层的场景,其中每个 CCSprite 都在其中.
I have a scene with a layer that contains a bunch of CCNodes with each one CCSprite in them.
在应用程序期间,我在主图层的位置周围移动,以便以某种方式平移"相机.(即我翻译整个图层以便视口发生变化).
During the application, I move around the position of the main layer, so that I "pan" around a camera in a way. (i.e. I translate the entire layer so that the viewport changes).
现在我想确定 CCNode 在屏幕坐标中的绝对位置.position 属性返回相对于父节点的位置,但我真的希望将其转换为它在屏幕上的实际位置.
Now I want to determine the absolute position of a CCNode in screen coordinates. The position property return the position relative to the parent node, but I really would like this transformed to its actual position on screen.
另外,作为一个额外的好处,如果我可以将此位置表示为坐标系,其中 0,0 映射到屏幕的左上角,而 1,1 映射到屏幕的右下角,那就太棒了.(所以我与所有设备保持兼容)
Also, as an added bonus, it would be awesome if I could express this position as coordinate system where 0,0 maps to the upper left of the screen, and 1,1 maps to the lower right of the screen. (So I stay compatible with all devices)
请注意,该解决方案最好适用于 CCNode 的任何层次结构.
Note that the solution should work for any hierarchy of CCNodes preferably.
推荐答案
每个 CCNode 及其后代都有一个名为 convertToWorldSpace:(CGPoint)p 的方法
Every CCNode, and descendants thereof, has a method named convertToWorldSpace:(CGPoint)p
这将返回相对于您的场景的坐标.
This returns the coordinates relative to your scene.
获得此坐标后,翻转 Y 轴,因为您希望 0,0 位于左上角.
When you have this coordinate, flip your Y-axis, as you want 0,0 to be in the top left.
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];
这篇关于Cocos2D CCNode 在屏幕绝对坐标中的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!