我试图通过添加以下代码行来使我的游戏在didMove函数中结束:
if ((player.physicsBody?.velocity.dx)! < CGFloat(10.0)) {
gameOver()
} else if ((player.physicsBody?.velocity.dy)! < CGFloat(10.0)) {
gameOver()
}
这是gameOver()函数:
func gameOver() {
score = Watch.elapsedTime
player.physicsBody?.contactTestBitMask = 0
player.physicsBody?.collisionBitMask = 0
player.physicsBody?.categoryBitMask = 0
hitSoundEffect?.stop()
bounceSoundEffect?.stop()
Watch.stop()
motionManager.stopAccelerometerUpdates()
if score > highScore {
UserDefaults.standard.set(Int(score), forKey: "highScore")
}
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc1 = storyboard.instantiateViewController(withIdentifier: "gameoverVC")
vc1.modalPresentationStyle = .fullScreen
vc1.modalTransitionStyle = .crossDissolve
self.getTopMostViewController()?.present(vc1, animated: true, completion: nil)
}
我想要这样,如果玩家的速度降至10以下,则游戏应该结束并移至下一个viewController。
即使运行了gameOver函数,gameScene仍然继续检测碰撞并报告碰撞,如何停止碰撞?
这是带有位掩码的didBegin函数:
let PlayerHitCategory: UInt32 = 5;
let ObjectHitCategory: UInt32 = 4;
let WallHitCategory: UInt32 = 3;
player.physicsBody?.categoryBitMask = PlayerHitCategory
player.physicsBody?.collisionBitMask = ObjectHitCategory | WallHitCategory
player.physicsBody?.contactTestBitMask = ObjectHitCategory
object.physicsBody?.contactTestBitMask = ObjectHitCategory | PlayerHitCategory
object.physicsBody?.categoryBitMask = ObjectHitCategory
object.physicsBody?.collisionBitMask = ObjectHitCategory | PlayerHitCategory
physicsBody.categoryBitMask = WallHitCategory
physicsBody.collisionBitMask = 0
physicsBody.contactTestBitMask = PlayerHitCategory
func didBegin(_ contact: SKPhysicsContact) {
// print("didBeginContact entered for \(String(describing: contact.bodyA.node!.name)) and \(String(describing: contact.bodyB.node!.name))")
let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask
switch contactMask {
case PlayerHitCategory | ObjectHitCategory:
hitSound()
playerDisplacement()
print("Collided with object")
case PlayerHitCategory | WallHitCategory:
bounceSound()
print("Collided with wall")
default: break
}
}