【问题标题】:Collisions are getting detected multiple times even though it is just a single collision即使只是一次碰撞,也会多次检测到碰撞
【发布时间】:2022-01-21 15:34:56
【问题描述】:
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")
    
    }
    
}

我正在尝试正确检测碰撞。每当我的播放器撞到另一个物体时,控制台就会记录多个碰撞而不是单个碰撞。所以我想知道是否有任何方法可以解决这个问题。

【问题讨论】:

    标签: ios swift sprite-kit collision-detection game-physics


    【解决方案1】:

    我假设您从didBegin 收到多条消息,似乎是一次冲突?

    didBegin(Contact:) 似乎被两个节点之间的每个接触点调用,而不仅仅是单个联系人。您无法阻止多次调用 didBegin(contact:),因此您必须对联系人处理进行编码以考虑到这一点。

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

    查看链接到进一步讨论的这个答案:https://stackoverflow.com/a/43064543/1430420

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多