我正在重新使用 DemoBots 中使用的方法进行接触检测。由于我的代码的工作方式和 DemoBots 的编写方式之间存在差异,我遇到了一个问题。在 DemoBots 中,组件 RenderComponent 有一个变量 ' node
'
let node = EntityNode()
init(entity: GKEntity) {
node.entity = entity
}
在我的代码中,我没有使用动画,所以我的 RenderComponent 等价物有点复杂。变量“节点”已被使用并绑定到物理体,所以我创建了一个新变量“ entityNode
”
let node: SKSpriteNode
let entityNode = EntityNode()
init(entity: GKEntity, nodeTemplate: SKSpriteNode) {
node = SKSpriteNode(imageNamed: "animal")
entityNode.entity = entity
}
在 handleContact: 方法中,我尝试了两种解决方案来获取对实体的引用。选项1:
let entityA = (contact.bodyA.node as? EntityNode)?.entity
let entityB = (contact.bodyB.node as? EntityNode)?.entity
对此运行 print() 检查会返回这两个实体的 nil 值。这很合乎逻辑,因为我应该寻找一个名为 ' entityNode
' 的属性来查找实体。当我将其更改为选项 2 时:
let entityA = (contact.bodyA.entityNode as? EntityNode)?.entity
let entityB = (contact.bodyB.entityNode as? EntityNode)?.entity
我收到一个错误,即physicsBody 没有成员“ entityNode
。” 我已经尝试了很多其他的事情,比如查找与contactBody关联的实体,但是我得到另一个错误,它说后续代码正在寻找一个可选的。我已经尝试摆脱“如果”,但它只是将问题转移到下一个contactCallBack
电话。
if let notifiableEntity = entityA as? ContactNotifiableType, otherEntity = entityB where aWantsCallback {
contactCallback(notifiableEntity, otherEntity)
}
有什么想法可以解决这个问题以使contactCallBack
电话正常工作吗?