gpt4 book ai didi

swift - spriteKit didBeginContact 无法添加Child

转载 作者:行者123 更新时间:2023-11-30 14:00:46 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com