Search code examples
ioscocos2d-iphoneresolutionccsprite

Issues with sprite location in cocos2d


I have a sprite, that I'd like to use as background image(using cocos2d).

CCSprite *abc =[CCSprite spriteWithImageNamed:@"background.png"];    
abc.position  = ccp(self.contentSize.width/2,self.contentSize.height/2);

First image is original, second one is a screenshot from the simulator. Resolution of the image is 640/1136. What should I do to fit all space of the screen normally? How schould I locate it?

enter image description here

enter image description here


Solution

  • The code you are using is correct.

    The result you are getting is not what you expected because you probably loaded a Retina Image on a non Retina Screen.

    Check out Cocos2d Naming conventions here for more info.

    For the background image you chose of the sun, I am assuming that you want it to be always in the top right corner. (That makes more sense to me than centering it).

    Now an elegant solution to accomplish this would be to get your image for the 4 inch screen that you have already created, and define a rule so that it's top left corner is always at the top left corner of the screen. For the 3.5 inch screens this would be clipped.

    Now, first you want to define an anchor point as

    _background.anchorPoint = ccp(1.0f, 1.0f);
    

    This will tell Cocos to position your background relative to the top right corner.

    Now you can go on and position it so that it is always at the top corner of the screen.

    background.position = ccp(self.scene.bounds.size.width, self.scene.size.height);
    

    This would be the standard and best way to do it. Results and benefits:

    • Works on 3.5 and 4 inch screens without needing specific image sizes
    • Simple, no unnecessary code and especially UI_INTERFACE_IDIOM testing
    • The way most everybody does it

    Another way of positioning in the top right corner

    You can also check out the new positionType property for CCNode in the reference. CCPositionUnitNormalized can help you define a positioning rule similar to saying position this to the 100% width and 100% height of the parent container. It would be something like this.

    _background.positionType = CCPositionUnitNormalized;
    _background.position = ccp (1.0f, 1.0f);
    

    and have the same result if you prefer this syntax.