简体   繁体   English

在COCOS2D v3中子类化CCSprite

[英]Subclassing CCSprite in COCOS2D v3

Hi I recently updated to COCOS2D v3 and the code I used to use to subclass a CCSprite no longer works and I am getting an error when I try to assign values to my properties. 嗨,我最近更新到了COCOS2D v3,我用来为CCSprite子类化的代码不再起作用,当我尝试为属性分配值时出现错误。

@interface Alien : CCSprite
{

int _minMoveDuration;
int _maxMoveDuration;
int _hp;
}

@property (nonatomic, assign) int hp;
@property (nonatomic, assign) int minMoveDuration;
@property (nonatomic, assign) int maxMoveDuration;

@end

@interface SmallFastAlien: Alien
{

}
+(id)alien;
@end 

Inside the main file I then set my properties for the alien class: 然后在主文件中,为外来类设置属性:

#import "Alien.h"

@implementation Alien

@synthesize hp = _hp;
@synthesize minMoveDuration = _minMoveDuration;
@synthesize maxMoveDuration = _maxMoveDuration;

@end

@implementation SmallFastAlien

+ (id)alien
{
SmallFastAlien *alien = nil;
/*if ((alien = [[[super alloc] initWithSpriteFrameName:@"small-1.png"] autorelease]))
{

}*/
alien = [CCSprite spriteWithImageNamed:@"small-1.png"];

alien.hp = 1;
//alien.minMoveDuration = 3;
//alien.maxMoveDuration = 5;

return alien;
}

@end

However, I then get an error when the hp property is set. 但是,设置hp属性时,我会收到一条错误消息。 This did work in v2, but no longer works in v3 and gives the following error: 这确实在v2中起作用,但在v3中不再起作用,并出现以下错误:

-[CCSprite setHp:]: unrecognized selector sent to instance 0x10a4c5cb0

Any advice would be greatly appreciated. 任何建议将不胜感激。

You create a CCSprite, that's why: 您创建一个CCSprite,这就是为什么:

alien = [CCSprite spriteWithImageNamed:@"small-1.png"];

You ought to be creating an instance of your class, for instance: 您应该创建类的实例,例如:

alien = [SmallFastAlien spriteWithImageNamed:@"small-1.png"];

PS: ivar declaration in @interface and @synthesize in @implementation are unnecessary, so is the assign keyword (specifically for int and other primitive data types). PS: @interface ivar声明和@implementation中的@synthesize都是不必要的,所以assign关键字也是如此(特别是对于int和其他原始数据类型)。 Xcode auto-synthesizes ivars (with underscore prefix) and getter/setter, assign only affects object ( id ) types. Xcode自动合成ivars(带有下划线前缀)和getter / setter,分配仅影响对象( id )类型。 You can shorten your code to: 您可以将代码缩短为:

@interface Alien : CCSprite

@property (nonatomic) int hp;
@property (nonatomic) int minMoveDuration;
@property (nonatomic) int maxMoveDuration;

@end


@implementation Alien

@end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM