简体   繁体   中英

How to add SCNNode as a child to parent without changing relative position, size and scale in world coordinates

I have two SCNNodes, nodeCh and nodePrnt . Their world coordinates are available and their relative position/size/angle should remain the same.

I want to add nodeCh to the nodePrnt as a child, by using - (void)addChildNode:(SCNNode) method. In order to do that I should translate the world coordinates/size/angles of nodeCh in terms of relative position/scale/rotation of nodePrnt so that the relative positions/scale/sizes won't change comparing to the case when both nodes are added to scene.rootNode as children.

Clearly, I have to use some combination of transform operators. Currently I am using the following lines which work incorrectly:

SCNMatrix4 transform
    = [self.nodePrnt convertTransform:SCNMatrix4Identity
                              fromNode:nil];

nodeChld.transform = transform;

Conversion utils are indeed what you'll need to use. In your case:

nodeCh.transform = [nodePrnt convertTransform:SCNMatrix4Identity fromNode:nodeCh];

or

nodeCh.transform = [nodeCh convertTransform:SCNMatrix4Identity toNode:nodePrnt];

Here's a quick helper method inspired by SpriteKit.

Swift 5.2

extension SCNNode {
    func move(toParent parent: SCNNode) {
        let convertedTransform = convertTransform(SCNMatrix4Identity, to: parent)
        removeFromParentNode()
        transform = convertedTransform
        parent.addChildNode(self)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM