我正在使用SpriteKit解决一些碰撞检测问题。我在didBeginContact
中发射了正确的碰撞,这很棒。
现在我遇到了一个范围问题,我无法根据其中一个碰撞点击删除和添加场景中的孩子。第一次检测确实有效,但第二次检测失败。
这是正确调用的didBeginContact
函数。这两种方法都在我的根SKScene:
func didBeginContact(contact: SKPhysicsContact) {
if (contact.bodyA.categoryBitMask == ColliderType.Head && contact.bodyB.categoryBitMask == ColliderType.Food) {
//remove and place new food
//this one works great
self.placeFoodInRandomGridLocation()
} else if (contact.bodyA.categoryBitMask == ColliderType.Food && contact.bodyB.categoryBitMask == ColliderType.Body) {
//remove and place new food
//this one FAILS
self.placeFoodInRandomGridLocation()
}
}
func placeFoodInRandomGridLocation() {
snakeFood!.removeFromParent()
let randomX = arc4random_uniform((myGrid.columnCount))
let randomY = arc4random_uniform((myGrid.rowCount))
snakeFood = Food(size: CGSize(width: myGrid.snakeWide/2, height: myGrid.snakeHigh/2), gap: gapFactor)
snakeFood!.position = CGPoint(x: colLines[Int(randomX)], y: rowLines[Int(randomY)])
//THIS child does not appear for the 2nd collision. It DOES for the first.
self.addChild(snakeFood!)
}
struct ColliderType {
static let Head: UInt32 = 0
static let Food: UInt32 = 0b1
static let Body: UInt32 = 0b10
}
答案 0 :(得分:0)
在didBeginContact碰撞发生后,我无法直接更新snakeFood对象的位置。我能够在didBeginContact中跟踪一个布尔值,然后我可以在didSimulatePhysics中捕获它。这个解决方案效果很好:
func didBeginContact(contact: SKPhysicsContact) {
if (contact.bodyA.categoryBitMask == ColliderType.Head && contact.bodyB.categoryBitMask == ColliderType.Food) {
placeFood = true
} else if (contact.bodyA.categoryBitMask == ColliderType.Food && contact.bodyB.categoryBitMask == ColliderType.Body) {
placeFood = true
} else if (contact.bodyA.categoryBitMask == ColliderType.Body && contact.bodyB.categoryBitMask == ColliderType.Food) {
placeFood = true
}
}
func placeFoodInRandomGridLocation() {
let randomX = arc4random_uniform(UInt32(myGrid.columnCount))
let randomY = arc4random_uniform(UInt32(myGrid.rowCount))
snakeFood!.position = CGPoint(x: colLines[Int(randomX)], y: rowLines[Int(randomY)])
}
override func didSimulatePhysics() {
if (placeFood == true) {
placeFood = false
placeFoodInRandomGridLocation()
}
}