我正在SpriteKit中构建一个游戏,其中玩家试图避免与对象发生碰撞。每隔3到5秒就会创建一个对象,我试图找出一种方法,一旦它与屏幕底部发生冲突就从父版本中移除但是出于某种原因它会在游戏结束时进行游戏结束请参阅下面的代码在风景中。
import SpriteKit
class PlayScene: SKScene, SKPhysicsContactDelegate {
enum ColliderType: UInt32 {
case none = 0
case player1 = 1
case object = 2
case border = 4
case remove = 8
}
gameOver = false
let ground = SKNode()
ground.position = CGPoint(x: 0, y: 0)
ground.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: self.frame.size.width + 500, height: 1))
ground.physicsBody?.isDynamic = false
ground.physicsBody?.categoryBitMask = ColliderType.remove.rawValue
ground.physicsBody?.contactTestBitMask = ColliderType.object.rawValue
ground.physicsBody?.collisionBitMask = ColliderType.none.rawValue
character1.physicsBody!.categoryBitMask = ColliderType.player1.rawValue
character1.physicsBody!.contactTestBitMask = ColliderType.object.rawValue
character1.physicsBody!.collisionBitMask = ColliderType.object.rawValue | ColliderType.border.rawValue
object1.physicsBody!.categoryBitMask = ColliderType.object.rawValue
object1.physicsBody!.contactTestBitMask = ColliderType.player1.rawValue | ColliderType.remove.rawValue
object1.physicsBody!.collisionBitMask = ColliderType.player1.rawValue | ColliderType.border.rawValue | ColliderType.object.rawValue
if contact.bodyA.categoryBitMask == ColliderType.object.rawValue || contact.bodyB.categoryBitMask == ColliderType.object.rawValue {
gameOver == true
}
if contact.bodyA.categoryBitMask == ColliderType.remove.rawValue || contact.bodyB.categoryBitMask == ColliderType.remove.rawValue {
object1.removeFromParent()
// it runs this code as well as code above collision object with object but i want contact remove with object
}
答案 0 :(得分:1)
尝试在将来发布完整代码,而不是将一些随机位放在一起。
你的碰撞代码没有多大意义。它应该看起来更像是你检查播放器 - >对象和对象 - >删除,反之亦然
func didBegin(_ contact: SKPhysicsContact) {
let firstBody: SKPhysicsBody
let secondBody: SKPhysicsBody
// This way you only need to do 1 if statement for each collision.
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
} else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
// Player hit Object or Object hit Player
if (firstBody.categoryBitMask == ColliderType.player.rawValue) && (secondBody.categoryBitMask == ColliderType.object.rawValue) {
gameOver == true
}
// Object hit Remove or Remove hit Object
if (firstBody.categoryBitMask == ColliderType.object.rawValue) && (secondBody.categoryBitMask == ColliderType.remove.rawValue) {
// Remove object
firstBody.node?.removeFromParent()
}
}
我建议你阅读一些关于精灵工具包碰撞的更多教程,如果这让你感到困惑,还有很多可用的教程。
希望这有帮助