Swift 4 中的特定正面碰撞
Specific Head On Collision in Swift 4
我是 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()
}
}
您可以尝试计算两个碰撞节点之间的交点,然后只需检查结果帧的宽度和高度就足以检测碰撞侧,粗略的解释:
- 碰撞left/right
- 碰撞top/down
对于无限跑酷游戏,此检查应该足够了:
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
//...//
}
}
我是 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()
}
}
您可以尝试计算两个碰撞节点之间的交点,然后只需检查结果帧的宽度和高度就足以检测碰撞侧,粗略的解释:
- 碰撞left/right
- 碰撞top/down
对于无限跑酷游戏,此检查应该足够了:
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
//...//
}
}