Cocos2D CCNode在绝对坐标中的位置 [英] Cocos2D CCNode position in absolute screen coordinates

查看:756
本文介绍了Cocos2D CCNode在绝对坐标中的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一段时间,因为某种原因我没能找到答案。看起来很简单,但也许我只是在库中找不到正确的函数。

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.

我有一个场景包含一堆CCNodes一个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)

编辑:注意,解决方案应该适用于CCNodes的任何层次结构。

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在绝对坐标中的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆