Cocos2d on iPhone: Using Sprites Defined in Separate Class Files
I'm trying to draw two sprites on the same screen. I have defined the two sprite objects in two separate class files.
- If I comment out two lines (see "item 1" comment below) then I get a display as [a backgroundimage[background2.jpg] with a sprite[grossini.png] on the left side.
- If I uncomment the two lines I do not get the background image and sprite of (gameScreen.m). I get only the sprite [grossinis_sister1.png] defined in (enemy.m).
- But what I need is a [backgroundimage[background2.jpg]], sprite[grossini.png] and sprite [grossinis_sister1.png] in one screen.
This is implementation file of my first class:
#import "gameScreen.h"
#import "enemy.h"
@implementation gameScreen
-(id)init
{
if((self = [super init]))
{
CCSprite *backGroundImage = [CCSprite spriteWithFile:@"background2.jpg"];
backGroundImage.anchorPoint = ccp(0,0);
CCParallaxNode *voidNode = [CCParallaxNode node];
[voidNode addChild:backGroundImage z:-1 parallaxRatio:ccp(0.0f,0.0f) positionOffset:CGPointZero];
[self addChild:voidNode];
CGSize windowSize = [[CCDirector sharedDirector] winSize];
CCSprite *player = [CCSprite spriteWithFile:@"grossini.png"];
player.position = ccp(player.contentSize.width/2, windowSize.he开发者_如何转开发ight/2);
[self addChild:player z:0];
//eSprite = [[enemy alloc]init]; //<-- see item 1
//[self addChild:eSprite];
}
return self;
}
This is my implementation file of my second class:
#import "enemy.h"
#import "gameScreen.h"
@implementation enemy
-(id)init
{
if ((self = [super init]))
{
CGSize windowSize = [[CCDirector sharedDirector] winSize];
CCSprite *enemySprite = [CCSprite spriteWithFile:@"grossinis_sister1.png" ];
enemySprite.position = ccp(windowSize.width/2, windowSize.height/2);
[self addChild:enemySprite];
}
return self;
}
@end
The high level understanding you need is this. A screen contains 1 or many layers a layer contains sprites.
So create a screen and then add a layer to it and add the sprites to the layer you created. Of course one can have many screens and a screen can consists of many layers. But in a simple demo game create 1 screen, 1 layer, and add sprites to that layer.
See this link for more detail http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:basic_concepts.
I am unfamiliar with Cocos2d but the normal pattern is to have a object that would own both gamescreen and enemy sprites and manage both.
精彩评论