我正在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
}
最佳答案
将来尝试为此发布完整的代码,而不是将一些随机的位放在一起。
您的碰撞代码没有多大意义。它看起来应该更像这样,在其中检查玩家->物体和物体->移除,反之亦然
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()
}
}
我建议您阅读更多有关Sprite Kit碰撞的教程,如果您对此感到困惑,则有很多可用的教程。
希望这可以帮助
关于ios - 在SpriteKit中离开场景后如何删除SKNode,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39968479/