即使只是一次碰撞,也会多次检测到碰撞


func didBegin(_ contact: SKPhysicsContact) {
// Each contact has two bodies, but we do not know which two bodies
// first we will find the player body, and then use the other body to determine the contact type
let otherBody: SKPhysicsBody
// combine the two player physics categories into one bitmask using the bitwise OR operator
let playerMask = PhysicsCategory.player.rawValue | PhysicsCategory.damagedPlayer.rawValue
// Use the bitwise AND operator to find the penguin.
// This returns a positive number if body A's category is the same as either the player or damaged player
if contact.bodyA.categoryBitMask & playerMask > 0 {
// body A is the player, so we test body B
otherBody = contact.bodyB
}
else {
// body B is the player, so we test body A
otherBody = contact.bodyA
}

// Determine the type of contact
switch otherBody.categoryBitMask {
case PhysicsCategory.ground.rawValue:
print("hit the ground")
case PhysicsCategory.enemy.rawValue:
print("hit enemy, take damage")
case PhysicsCategory.coin.rawValue:
print("collect a coin, more wealthy")
case PhysicsCategory.powerup.rawValue:
print("gained a power up")
default:
print("Contact with no game logic")

}

}

我正在尝试正确检测碰撞。每当我的玩家击中另一个物体时,控制台就会记录多个碰撞,而不是一个碰撞。所以我想知道是否有办法解决这个问题。

我假设您从didBegin收到多条消息,这似乎是一次碰撞?

didBegin(Contact:)似乎是针对2个节点之间的每个接触点调用的,而不仅仅是针对单个接触。您无法阻止多次呼叫didBegin(contact:),因此您必须对联系人处理进行编码以将其考虑在内。

一种方法是使用userData字段(https://developer.apple.com/documentation/spritekit/sknode/1483121-userdata)在节点上标记接触处理已经发生,但这实际上取决于节点接触时想要发生什么,无论是增加分数、降低装甲值、从场景中移除阳极等。

请参阅以下链接到进一步讨论的答案:https://stackoverflow.com/a/43064543/1430420

最新更新