7
votes

I have a child node added to another node. I want to get the child nodes position with respect to the views coordinates and not the parent nodes coordinates

2

2 Answers

18
votes

Get the child node's position with respect to its parent, then use the convertPoint:fromNode: or convertPoint:toNode: method to convert from the parent node's coordinate system to the scene's coordinate system. (Remember, SKScene inherits from SKNode and is the root of the node hierarchy, so you can use it with either of those methods.) If you then need to work in the UIKit view coordinate space, use the scene's convertPointToView: method.

3
votes

If by 'view coordinates' you mean the scene coordinates, then check out this swift solution I use:

extension SKNode {
    var positionInScene:CGPoint? {
        if let scene = scene, let parent = parent {
            return parent.convert(position, to:scene)
        } else {
            return nil
        }
    }
}

Then you can get the scene position in the same manner you get the regular position. Here is an example:

let positionInParent = childNode.position
let positionInScene  = childNode.positionInScene? //optional return type

Note that the positionInScene property is optional for the same reason that the scene property of SKNode is optional, the node might not be added to a scene. In this case, you get nil. You could even reverse the process and add a setter, so you could position every node in the scene coordinates no matter how deeply it was buried.