kag359six kag359six - 7 months ago 122
Swift Question

SpriteKit - Converting point to scene coordinates gives wrong value

I want to convert the cell position to the scene's coordinates. Currently, the cell is a child of an invisible node. When the cell makes contact with virus, I get the position of cell. Confusingly, the position of cell is the same in its coordinates relative to its parent, as well as when the coordinates are converted to the scene. The position reads (0,0.002) but its actual position should be (0,50).

If I monitor the position by referencing the cell node directly (ex.

childNodeWithName("cell")
), it shows the correct position. I had originally assumed the issue had to do with down casting, but with or without it the position shows incorrectly. Why is this the case?

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

Answer

You are using the convertPoint method on the same object (self) that you are converting to (self), so you will always get the same point!

There are many issues with this snippet. For example, simple setting the attachedCell property of virus will not make the virus a child node of the virus.

If you want to do that, you must do so explicitly. Otherwise, the cell still is a child of whatever node it was before...

You want this:

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

Which will convert the position of the cell from the virus's coordinate system to the scene's coordinate system.