SpriteKit - 将点转换为场景坐标会给出错误的值

SpriteKit - Converting point to scene coordinates gives wrong value

我想将单元格位置转换为场景坐标。当前,该单元格是不可见节点的子节点。当细胞与病毒接触时,我得到细胞的位置。令人困惑的是,单元格的位置在其相对于其父级的坐标中是相同的,在坐标转换为场景时也是如此。该位置显示为 (0,0.002),但其实际位置应为 (0,50)。

如果我通过直接引用单元节点(例如 childNodeWithName("cell"))来监控位置,它会显示正确的位置。我最初认为这个问题与向下投射有关,但无论有没有它,位置都显示不正确。为什么会这样?

func didBeginContact(contact: SKPhysicsContact) {
    let bodyA = contact.bodyA
    let bodyB = contact.bodyB

    if bodyA.categoryBitMask & PhysicsCategory.Virus != 0
        && bodyB.categoryBitMask & PhysicsCategory.Cell != 0 {

        let virus = bodyA.node as! VirusNode
        virus.attachedCell = bodyB.node as? CellNode
        print(self.convertPoint(virus.attachedCell!.position, toNode: self)) //outputs (0,0.002)
    }
}

您在要转换为 (self) 的同一对象 (self) 上使用 convertPoint 方法,因此您将始终得到相同的点!

这段代码有很多问题。比如简单设置virus的attachedCell属性不会让病毒成为病毒的子节点

如果你想这样做,你必须明确地这样做。否则,该单元格仍然是它之前的任何节点的子节点...

你想要这个:

func didBeginContact(contact: SKPhysicsContact) {
    let bodyA = contact.bodyA
    let bodyB = contact.bodyB

    if bodyA.categoryBitMask & PhysicsCategory.Virus != 0
        && bodyB.categoryBitMask & PhysicsCategory.Cell != 0 {
        bodyB.node.removeFromParent()
        let virus = bodyA.node as! VirusNode
        virus.attachedCell = bodyB.node as? CellNode
        virus.addChild(bodyB.node)
        print(virus.convertPoint(virus.attachedCell!.position, toNode: self)) //should output properly
    }
}

这会将细胞的位置从病毒的坐标系转换到场景的坐标系。