gpt4 book ai didi

swift - 快速测试节点是否附加到物理主体

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

我在检测到 SKSpriteNode 之间的接触时调用的函数中获取附加到接触体 (SKPhysicsBody) 的节点。有时,我会收到错误,因为它无法将节点附加到接触体,因此我测试是否有一个节点可以避免此类错误。但警告告诉我它永远不会返回 false。自从我测试以来,我再也没有遇到过这样的错误,但我不确定它是否运行良好或者是否仍然会发生。你有什么想法吗?

//The actual code
func didBegin(_ contact: SKPhysicsContact) {
if (contact.bodyA.categoryBitMask == enemyCategory) && (contact.bodyB.categoryBitMask == shootCategory){ //test if it is the contact with I want to catch
let shootNode = contact.bodyB.node, shootNode != nil { // I test if there's a node attached to the enemyShootNode but it's supposed never to return false
let enemyNode = contact.bodyA.node, enemyNode != nil { // I test if there's a node attached to the shootNode but it's supposed never to return false
let enemySKNode = enemyNode as? SKSpriteNode
let shootSKNode = shootNode as? SKSpriteNode
// code
}
}
}
}

// The code with error
func didBegin(_ contact: SKPhysicsContact) {
if (contact.bodyA.categoryBitMask == enemyCategory) && (contact.bodyB.categoryBitMask == shootCategory){
let shootNode = contact.bodyB.node!
let enemyNode = contact.bodyA.node! // The error occurs here : "fatal error: unexpectedly found nil while unwrapping an Optional value"
let enemySKNode = enemyNode as? SKSpriteNode
let shootSKNode = shootNode as? SKSpriteNode
}
}

最佳答案

感谢您的建议,错误确实来自 SKPhysics 属性(didBegin 函数被调用了几次),但我没有设法修复。虽然我纠正了检查 Sprite 是否在这里的方式,并且没有更多警告或错误,所以我认为它工作得很好:

func didBegin(_ contact: SKPhysicsContact) {
if (contact.bodyA.categoryBitMask == enemyCategory) && (contact.bodyB.categoryBitMask == shootCategory) || (contact.bodyA.categoryBitMask == shootCategory) && (contact.bodyB.categoryBitMask == enemyCategory){
if var shootNode = contact.bodyB.node{
if var enemyNode = contact.bodyA.node{
// If the enemyNode and the shootNode don't respectively correspond to
if contact.bodyA.categoryBitMask == shootCategory {
shootNode = contact.bodyA.node!
enemyNode = contact.bodyB.node!
}
let enemySKNode = enemyNode as? SKSpriteNode
let shootSKNode = shootNode as? SKSpriteNode
}
}
}
}

关于swift - 快速测试节点是否附加到物理主体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46957616/

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