我在继承 SKSpriteNode 时遇到问题。这是我对子类的实现:
@implementation SSSquirrel
- (id) init {
if (self = [super init]) {
// Create Squirrel and physics body
SKSpriteNode *squirrel = [SKSpriteNode spriteNodeWithImageNamed:@"squirrelNormal"];
squirrel.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:squirrel.size.width/2 - 10];
squirrel.physicsBody.dynamic = NO;
squirrel.physicsBody.affectedByGravity = NO;
squirrel.physicsBody.restitution = 0.8;
squirrel.physicsBody.friction = 0.1;
squirrel.zPosition = 1.0;
[self addChild:squirrel];
}
return self;
}
@end
然后我在我的主要游戏场景中创建了一只松鼠:
SSSquirrel *squirrel1 = [[SSSquirrel alloc] init];
squirrel1.position = CGPointMake(offset, self.frame.size.height - offset);
[self addChild:squirrel1];
一切都创建得很好。然而,在游戏过程中,我尝试在触摸开始时“暂停”松鼠物理身体,然后在触摸结束时重新启用它(tempSquirrelBody 是场景的 SKPhysicsBody 实例变量)。基本上,我试图给出松鼠在用户触摸屏幕时向用户移动并越过其他对象的错觉。
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
/* Called when a touch begins */
for (UITouch *touch in touches) {
tempSquirrelBody = squirrel1.physicsBody;
squirrel1.physicsBody = nil;
CGPoint newPosition = squirrel1.position;
newPosition.x -= 60;
newPosition.y += 60;
squirrel1.position = newPosition;
squirrel1.texture = [SKTexture textureWithImageNamed:@"squirrelUp"];
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
/* Called when a touch ends */
for (UITouch *touch in touches) {
CGPoint newPosition = squirrel1.position;
newPosition.x += 60;
newPosition.y -= 60;
squirrel1.position = newPosition;
squirrel1.texture = [SKTexture textureWithImageNamed:@"squirrelNormal"];
squirrel1.physicsBody = tempSquirrelBody;
}
}
不幸的是,这不起作用;当physicsbody应该设置为nil时,物理体没有被暂停,松鼠会与其他物体发生碰撞。当我将代码从我的 SSSquirrel 类移动到游戏场景时,它可以工作。我做错了什么?
谢谢!