swift - spriteKit didBeginContact 无法添加Child

标签 swift sprite-kit

我正在解决 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
}

最佳答案

在 didBeginContact 碰撞触发后,我无法直接更新 SnakeFood 对象的位置。我能够在 didBeginContact 中跟踪 bool 值,然后可以在 didSimulatePhysics 中捕获该 bool 值。这个解决方案效果很好:

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()
    }
}

关于swift - spriteKit didBeginContact 无法添加Child,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33027583/

相关文章:

ios - 镜像已固定子节点的 SpriteKit 节点

swift - 如何快速将属性观察器添加到 NSProgress?

swift - 重新计算图表中不同比例的值

ios - 为什么创建大量 SKNode 需要这么长时间

swift - 在 didBeginContact 中更改单个节点的纹理

swift - 如何在 SpriteKit 中将一个节点 "glue"到另一个节点?

Swift 3 HTTP 请求未通过

ios - 设置 UIBezierPath 对象的位置

swift - 发送本地通知

swift - SceneKit:在 SCNView 上渲染 SpriteKit 粒子系统时应用程序崩溃,当所有代码似乎都是系统代码的一部分时如何调试