Thursday, 10 January 2013

Cocos2d position best practice

This will be a short post about the best way to handle position in your Cocos2d project.




Positions are noted in points (CGpoint, these can also be used to calculate vectors). This is so that even though the screen resolutions of devices may differ (such as retina and non-retina iPhones), the relative position of sprites on the screen stays the same. An original iPhone has a resolution of 320 x 480 in pixels, and the same resolution in points. An iPhone 4 has twice the pixel resolution, but still a 320 x 480 point resolution.
            Because the new iPhone 5 (and iPads) bring a different screen ratio, it’s best practice to not measure positions in an absolute fashion, but relative to the screen. Please look at the following example (note that using properties or methods to change the position of a sprite makes no difference):

CCSprite*sprite=[CCSprite spriteWithFile:@"Sprite.png"];
        [layer addChild:sprite];

        sprite.position=ccp(240, 160);      //here we change the sprite's position 
//using a property to an absolute number, which would be in the middle of the screen on
// an original iPhone but more to the left on an iPhone 5
        
        CGSize screenSize=  [[CCDirector sharedDirector]winSize]; //here we create a
//CGSize (that has a width and height variable) with the width and hight of the screen
        
        [sprite setPosition:ccp(screenSize.width/2, screenSize.height/2)]; // here we
 //change the sprite's position using the setter method setPosition to a relative 
//position. Now the sprite will be positioned in the middle of the screen on all devices.

No comments:

Post a Comment