Cocos2D CCNode Position in Absolute Screen Coordinates

I looked around for a while, and for some reason I could not find the answer. It seems simple enough, but maybe I just can't find the function I need in the library.

I have a scene with a layer that contains a bunch of CCNodes with each of them CCSprite.

During the application, I navigate the main layer to β€œpan” around the camera in some way. (i.e. translate the entire layer so that the viewport changes).

Now I want to determine the absolute position of the CCNode in the screen coordinates. The position property returns the position relative to the parent node, but I really would like this to transform its actual position on the screen.

In addition, as an added bonus, it would be great if I could express this position as a coordinate system, where 0,0 displays in the upper left corner of the screen, and 1,1 in the lower right corner of the screen. (Thus, I remain compatible with all devices)

Edit: Note that the solution should work for any CCNodes hierarchy.

+6
source share
1 answer

Each CCNode and its descendants have a method called convertToWorldSpace: (CGPoint) p

This returns the coordinates relative to your scene.

When you have this coordinate, flip the Y axis, since you want 0,0 to be in the upper left corner.

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]; 
+18
source

Source: https://habr.com/ru/post/886549/


All Articles