Pages

Cocos2d-x: Coordinate System

Thursday, March 28, 2013

To understand the coordinate system of a game engine is a fundamental topic. In this tutorial I would like to describe the coordinate system of Cocos2d-x. The same concept is also applicable for Cocos2d game engine. You can also visit the Cocos2d-x Official Wiki Page which describes Cocos2d-x coordinate system briefly.

2D World Coordinate System


As cocos2d-x is a 2d game engine, we only use x-axis and y-axis to represent our coordinate system. Again, cocos2d-x uses OpenGL API to draw and manipulate objects. OpenGL use "right handed coordinate system" :

So, in cocos2d-x games,
  • The origin (x=0, y=0) is in the bottom-left corner of screen, which means the screen is in the first quartile of right-handed cartesian coordinate system, 
  • X axis starts at the left side of the screen and increase to the right; 
  • Y axis starts at the bottom of the screen and increase upwards.
Please take a look to the picture below to clear the understandings:


Place Objects on Screen


In Cocos2d-x, every class derived from CCNode (Ultimate cocos2d-x class) will have a anchorPoint property. When determining where to draw the object (sprite, layer, whatever), cocos2d-x will combine both properties position and anchorPoint. Also, when rotating an object, cocos2d-x will rotate it around its anchorPoint.

To set position or anchorPoint, we need to create a point by using a macro named ccp(x,y) or a function CGPointMake(x, y). Now, we create a sprite as a gray parent and another sprite as blue child. Set parent's position to ccp(100,100) and child's anchor point in the center of circle.
CCSprite* parent = CCSprite::create("parent.png");
parent->setAnchorPoint(ccp(0, 0));// Anchor Point set to origin
parent->setPosition(ccp(100, 100));// Set position to (100,100)
addChild(parent);

//create child 
CCSprite* child = CCSprite::create("child.png");
child->setAnchorPoint(ccp(0.5, 0.5));// Set anchor point with respect to parent
child->setPosition(ccp(0, 0));// Set position
parent->addChild(child);//Add child sprite into parent sprite.

As, the parent position is set to (100,100) point and its anchor point is set to (0,0) its effective position is (100,100) on the screen. But the child object is placed on the basis of its parent object. So, the child will be drawn on screen having center at (100,100).

To explore more on coordinate system of Cocos2d-x game engine please visit the official wiki page of Cocos2d-x.

No comments:

Post a Comment