我在继承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;
}
}
遗憾的是,这不起作用;当物理体被设置为零时,物理体不会被悬浮,松鼠会与其他物体发生碰撞。当我将代码从我的SSSquirrel类移动到游戏场景时,它可以工作。我做错了什么?
谢谢!
答案 0 :(得分:1)
仅将collisionBitMask
设置为0
而不是将整个physicsBody
设置为nil
会不会更容易?
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
/* Called when a touch begins */
for (UITouch *touch in touches) {
squirrel1.physicsBody.collisionBitMask = 0;
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.collisionBitMask = 0xFFFFFFFF;
}
}