我有一個應用程序,包含三個精靈節點ball1,ball2,ball3。他們通過向上,向下,向右,向左傾斜設備來移動現場。一切工作正常。 我想添加一個效果,其中任何兩個球接觸(碰撞)聲音播放。我使用的是SpriteKit,每個球都有一個physicalBody,他們有一個球形屬性,我有precisionCollision是的,categoryBitMask設置爲每個球的ballCategory1,2和3。 (或者我可以只使用一個類別) 我已經嘗試過如何做到這一點的各種教程,但似乎沒有任何工作。當兩個節點相撞時播放聲音
我已經嘗試使用Ray Wenderlich的例子和我的tweek。但是,
//這裏是我的三類
static const uint32_t ballCategory = 0x1 << 1;
static const uint32_t ballCategory2 = 0x1 << 2;
static const uint32_t ballCategory3 = 0x1 << 3;
//這是我的三個節點
ball = [SKSpriteNode spriteNodeWithImageNamed:@"mankala piece"];
ball.scale = 1;
ball.position = CGPointMake(600, 500);
ball.physicsBody =
[SKPhysicsBody bodyWithCircleOfRadius:(ball.size.width/2)];
ball.physicsBody.usesPreciseCollisionDetection = YES;
ball.physicsBody.categoryBitMask = ballCategory;
ball.physicsBody.collisionBitMask = ballCategory2|ballCategory|ballCategory3;
ball.physicsBody.affectedByGravity = NO;
[self addChild:ball];
ball2 = [SKSpriteNode spriteNodeWithImageNamed:@"mankala piece"];
ball2.scale = 1;
ball2.position = CGPointMake(350, 200);
ball2.physicsBody =
[SKPhysicsBody bodyWithCircleOfRadius:(ball2.size.width/2)];
ball2.physicsBody.usesPreciseCollisionDetection = YES;
ball2.physicsBody.categoryBitMask = ballCategory2;
ball2.physicsBody.collisionBitMask = ballCategory2|ballCategory|ballCategory3;
ball2.physicsBody.affectedByGravity = NO;
[self addChild:ball2];
ball3 = [SKSpriteNode spriteNodeWithImageNamed:@"mankala piece"];
ball3.scale = 1;
ball3.position = CGPointMake(500, 400);
ball3.physicsBody =
[SKPhysicsBody bodyWithCircleOfRadius:(ball3.size.width/2)];
ball3.physicsBody.usesPreciseCollisionDetection = YES;
ball3.physicsBody.categoryBitMask = ballCategory3;
ball3.physicsBody.collisionBitMask = ballCategory2|ballCategory|ballCategory3;
ball3.physicsBody.affectedByGravity = NO;
[self addChild:ball3];
//這裏是我修改後的代碼聯繫
- (void)didBeginContact:(SKPhysicsContact *)contact
{
SKPhysicsBody *firstBody, *secondBody;
if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask)
{
firstBody = contact.bodyA;
secondBody = contact.bodyB;
}
else
{
firstBody = contact.bodyB;
secondBody = contact.bodyA;
}
if ((firstBody.categoryBitMask & ballCategory) != 0)
{
NSLog(@"click");
}
if ((firstBody.categoryBitMask & ballCategory2) != 0)
{
NSLog(@"click2");
}
if ((firstBody.categoryBitMask & ballCategory3) != 0)
{
NSLog(@"click3");
}
}
但仍然沒有任何反應。
有人在spriteKit中使用碰撞。只是想在兩個不同的精靈節點接觸時播放聲音。
您可以使用[playSoundFileNamed]播放聲音文件(https://developer.apple.com/library/ios/documentation/SpriteKit/Reference/SKAction_Ref/#//apple_ref/occ/clm/SKAction/playSoundFileNamed:waitForCompletion :)。您需要將聲音文件添加到應用程序的包中。 – 0x141E