在Swift 4中碰撞的特定负责人

时间:2018-01-28 06:02:41

标签: swift sprite-kit skphysicsbody

我是iOS开发的新手,我做了一个无限的亚军游戏。正如您在下面的函数中看到的那样,播放器在与障碍物碰撞时会死亡。但是,只要玩家与障碍物的任何一侧发生碰撞,玩家就会死亡。如何将此碰撞检测限制在障碍物框架的特定一侧?

func didBegin(_ contact: SKPhysicsContact) { //so the player can't jump while in the air
    var firstBody = SKPhysicsBody()
    var secondBody = SKPhysicsBody()

    if contact.bodyA.node?.name == "Player" {
        firstBody = contact.bodyA
        secondBody = contact.bodyB
    } else {
        firstBody = contact.bodyB
        secondBody = contact.bodyA
    }

    if firstBody.node?.name == "Player" && secondBody.node?.name == "Ground" { //if colliding with ground
        canJump = true //can jump when on ground
    }

    if firstBody.node?.name == "Player" && secondBody.node?.name == "Bus" || firstBody.node?.name == "Player" && secondBody.node?.name == "Obstacle" {
        // kill player and prompt buttons
        playerDied()
    }
}

1 个答案:

答案 0 :(得分:0)

您可以尝试计算两个碰撞节点之间的交点,然后只检查结果帧的宽度和高度应该足以检测碰撞侧,这是一个粗略的解释:

  1. 左/右碰撞
  2. enter image description here

    1. 碰撞上/下
    2. enter image description here

      对于无限的亚军游戏,这项检查应该足够了:

      if firstBody.node?.name == "Player" && secondBody.node?.name == "Obstacle" {
          let intersection = firstBody.node!.frame.intersection(secondBody.node!.frame)
          if intersection.height > intersection.width { // collision left/right
              playerDied()
          } else { // collision top/down
             //...//
          }
      }