我最近决定将我的sprite子类化,但我有点不知道如何将它们添加到场景中。目前,我已经使用...的新File>Cocos2d>CCNode>Subclass创建了我的CCSprite子类。CCSprite。然后,我在Sprite.h文件中创建了我的sprite:
@interface Mos : CCSprite {
CCSprite *mos;
}完成后,在Sprite.m中,我编写了以下代码:
@implementation Mos
-(id) init
{
if( (self=[super init])) {
mos = [CCSprite spriteWithFile:@"sprite_mos.png"];
}
return self;
}我想知道的是如何将这个精灵添加到我的游戏场景中。
发布于 2012-02-24 16:17:53
下面是如何像documentation所说的那样正确地将CCSprite子类化:
@interface Mos : CCSprite {
// remove the line CCSprite *mos;
}
@implementation Mos
// You probably don't need to override this method if you will not add other code inside of it
-(id) initWithTexture:(CCTexture2D*)texture rect:(CGRect)rect
{
if( (self=[super initWithTexture:texture rect:rect]))
{
}
return self;
}
+ (id)sprite
{
return [Mos spriteWithFile:@"sprite_mos.png"];
}
@end然后,在您的代码中,您可以正常使用Mos:
Mos *mos = [Mos sprite];
[scene addChild:mos];发布于 2012-02-24 15:43:25
与添加CCSprites和其他类的方式相同。
Mos *newMos = [[Mos alloc] init];
// set coordinates and other properties
[scene addChild:newMos];
[newMos release];编辑:
@interface Mos : CCSprite {
// some member variables go here
}
@implementation Mos
-(id)init
{
CCTexture2D *texture = [[CCTextureCache sharedTextureCache] addImage:@"sprite_mos.png"];
if( texture ) {
CGRect rect = CGRectZero;
rect.size = texture.contentSize;
// set members to some values
return [self initWithTexture:texture rect:rect];
}
[self release];
return nil;
}然后在你的场景类中
// ...
Mos *obj = [[Mos alloc] init];
// set position, etc
[scene addChild:obj];
[obj release];
// ...https://stackoverflow.com/questions/9426682
复制相似问题