Working with the Myriad Coordinate Systems Available in Cocos2d
Lately, I find myself spending more of my free time working on a little game using Cocos2d. One of the things I was surprised to discover is that there’s not just a single coordinate system — there are four (that I know of — please correct me if I’m wrong).
The four I know of:
Core Graphics space
Open GL space
Node space relative to anchor point
I wasn’t totally clear on these going in, and I regret it. I ended up writing a lot of code that mish-mashed these and had to refactor it all.
Most likely you’re going to be processing a touch input on an iOS device and translating that to a coordinate system inside of a Cocos2d node (most likely a CCLayer) as such:
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView: [touch view]];
CGPoint glPoint = [[CCDirector sharedDirector] convertToGL:point];
CGPoint nodePoint = [self convertTouchToNodeSpace:touch];
CGPoint nodePointAR = [self convertTouchToNodeSpaceAR:touch];
With that in mind, here’s how I understand them:
Core Graphics (point) — This is what you normally work in if you’re accustomed to iOS development with UIKit and similar APIs.
CGPoint(0, 0) is in the top left corner of the screen and ascending Y values go down towards the bottom of the screen.
Open GL (glPoint) — This coordinate system has
(0, 0) in the bottom left of the screen, and ascending Y values go up towards the top of the screen.
Node space (nodePoint) — This space is relative to the origin of the reference node with which you are observing the point, and follows the same rules as the Open GL system. If your node is full-screen and unshifted (e.g. a default CCLayer), this coordinate system is exactly the same as the Open GL system.
Node space relative to anchor point (nodePointAR) — In Cocos2d, the default anchor point of any node is its center point. This coordinate system is relative to that center point. If you redefine the anchor point, this system is adjusted.
The big gotcha that I ran into was that I was doing something frowned upon in Cocos2d: shifting Layers! I was then using the Node space throughout my code but expecting points to resolve to Open GL space. So, word to wise: understand these coordinate systems going in, and don’t shift the position of your Layers!