我已经编写了SKSpriteNode的子类来表示我在游戏中多次使用的鳍状肢。我试图通过设置子sprite颜色属性来设置这些颜色,但这似乎只适用于我的精灵的一个实例,无论我试图设置哪一个。请有人告诉我我做错了什么或建议更好的方法。我只是希望能够将我的精灵子类的不同实例设置为不同的颜色。
我的SKSpriteNode子类如下:
#import "RSPaddleSprite.h"
@implementation RSPaddleSprite
SKSpriteNode *sprite;
-(id)init{
if (self = [super init]) {
sprite = [SKSpriteNode spriteNodeWithImageNamed:@"paddle2.png"];
[self addChild: sprite];
}
return self;
}
-(id)initWithImageNamed:(NSString *)name{
if (self = [super init]) {
sprite = [SKSpriteNode spriteNodeWithImageNamed:name];
[self addChild: sprite];
}
return self;
}
//function applies physics body to sprite when required
-(void)applyPhysicsBody{
self.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(sprite.size.width/4, sprite.size.height )];
self.physicsBody.affectedByGravity = FALSE;
self.physicsBody.mass = 0.1;
self.physicsBody.dynamic = TRUE;
}
//function sets color of sprite when required
-(void) setPaddleColor:(SKColor*)color{
sprite.color = color;
sprite.colorBlendFactor = 0.9;
}
@end
我在我的场景中调用子类函数如下:
//initialise paddles, position them, add physics and add to scene
paddle1 = [[RSPaddleSprite alloc ]initWithImageNamed:@"paddle1.png"];
paddle1.position = CGPointMake(self.frame.size.width/5,(self.frame.size.height/2)+30);
[paddle1 applyPhysicsBody];
[self addChild:paddle1];
paddle2 = [[RSPaddleSprite alloc ]initWithImageNamed:@"paddle1.png"];
paddle2.position = CGPointMake((self.frame.size.width/5)*4,(self.frame.size.height/2)+30);
[paddle2 applyPhysicsBody];
[self addChild:paddle2];
paddle3 = [[RSPaddleSprite alloc ]initWithImageNamed:@"paddle1.png"];
paddle3.position = CGPointMake((self.frame.size.width/3),120);
[paddle3 applyPhysicsBody];
[self addChild:paddle3];
paddle4 = [[RSPaddleSprite alloc ]initWithImageNamed:@"paddle1.png"];
paddle4.position = CGPointMake((self.frame.size.width/3)*2,120);
[paddle4 applyPhysicsBody];
[self addChild:paddle4];
//set paddle to appropriate color
[paddle1 setPaddleColor:[SKColor colorWithRed:0.15 green:0.15 blue:0.55 alpha:1.0]];
[paddle2 setPaddleColor:[SKColor colorWithRed:0.15 green:0.15 blue:0.55 alpha:1.0]];
[paddle3 setPaddleColor:[SKColor colorWithRed:0.15 green:0.15 blue:0.55 alpha:1.0]];
[paddle4 setPaddleColor:[SKColor colorWithRed:0.15 green:0.15 blue:0.55 alpha:1.0]];
答案 0 :(得分:1)
@implementation RSPaddleSprite
SKSpriteNode *sprite;
这使得“sprite”成为一个全局变量,所以你实际上只有sprite
引用了一个实例。
这是使sprite
成为ivar的正确形式:
@implementation RSPaddleSprite
{
SKSpriteNode *sprite;
}
更正确地坚持Cocoa命名约定,其中ivars以下划线为前缀:
@implementation RSPaddleSprite
{
SKSpriteNode *_sprite;
}