iOS spriteKit child nodes position with respect to view coordinates

霸气de小男生 提交于 2019-12-23 08:05:05

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/21865357/ios-spritekit-child-nodes-position-with-respect-to-view-coordinates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!