Swift spriteKit didBeginContact无法添加Child
我正在用SpriteKit解决一些碰撞检测问题。我在didBeginContact中触发了正确的碰撞,这很好 现在,我遇到了一个范围问题,我无法根据一次碰撞在场景中删除和添加子对象。第一次检测确实有效,但第二次检测失败 下面是正确调用的didBeginContact函数。这两种方法都在我的根场景中:Swift spriteKit didBeginContact无法添加Child,swift,sprite-kit,Swift,Sprite Kit,我正在用SpriteKit解决一些碰撞检测问题。我在didBeginContact中触发了正确的碰撞,这很好 现在,我遇到了一个范围问题,我无法根据一次碰撞在场景中删除和添加子对象。第一次检测确实有效,但第二次检测失败 下面是正确调用的didBeginContact函数。这两种方法都在我的根场景中: func didBeginContact(contact: SKPhysicsContact) { if (contact.bodyA.categoryBitMask ==
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
}
在didBeginContact碰撞触发后,我无法直接更新蛇食对象的位置。我能够在didBeginContact中跟踪布尔值,然后在didBeginContact中捕获。此解决方案效果良好:
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()
}
}
注意,我也尝试过仅仅定位蛇食,而不是移除和添加。这也失败了。你确定在else中,如果bodyA是食物,而不是身体?我建议测试哪个位掩码的值较低,然后将其与值较低的ColliderType进行比较。我还应该确定两个冲突都成功地调用了placefoodinrandomgrid location方法。您能发布位掩码值的声明吗?添加了位掩码值。另外请注意,我不再添加子级。我只是重新定位。