سؤال

I need to place a sprite at the bottom of the screen independently from resolution using cocos2d for iPhone, so that if a sprite is at the bottom on iPhone 5/5s, it will be at the bottom even on iPhone 4/4s.

The following code works on iPhone5/5s resolution, but not on the previous iPhone model:

ground1 = [CCSprite spriteWithImageNamed:@"ground1.png"];
ground1.position  = ccp(self.contentSize.width/2,self.contentSize.height/2-259);
[self addChild:ground1];

What can I do?

هل كانت مفيدة؟

المحلول

CGSize size = [[CCDirector sharedDirector]viewSize];
ground1 = [CCSprite spriteWithImageNamed:@"ground1.png"];
ground1.position  = ccp(size.width/2,[ground1 boundingBox].size.height/2);
[self addChild:ground1];

First of all you need the size of the view. In Cocos2D you get that value calling the CCDirector and getting its viewSize. After that, you create the sprite as you did. Now the important step is to position the sprite. Now you have your viewSize stored in 'size' so you get the X value by doing: size.width/2.

Now you have your sprite centered on X. Now let's position it over Y. You want your sprite to be at the bottom. So you need to calculate the point as I show you in this picture:

enter image description here

So the Y value is exactly height/2 of the sprite's size. We can get this value by calling the method:[sprite boundingBox] that returns the size of the sprite.

In conclusion, we have our sprite centered on X (size.width/2) and at the bottom ([sprite boundingBox].size.height/2)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top