[cocos creator] Modify the parent node of the node, keeping the absolute position unchanged

To replace a node with another parent node while keeping its absolute position in the world coordinate system, you can follow these steps:

var node = cc.find("Canvas/Node"); // 替换为你的节点路径
var newParent = cc.find("Canvas/NewParent"); // 替换为新的父节点路径

// 将节点从当前父节点中移除
node.removeFromParent(false);

// 计算节点在世界坐标系中的位置
var worldPosition = node.convertToWorldSpaceAR(cc.Vec2.ZERO);

// 将节点设置为新的父节点
node.setParent(newParent);

// 根据之前计算的世界坐标位置,重新设置节点的位置
node.setPosition(newParent.convertToNodeSpaceAR(worldPosition));

In the above code, we first use the cc.find() method to find the target node and the new parent node. Then, use removeFromParent(false) to remove the node from its current parent, retaining its world position.

Next, use the convertToWorldSpaceAR(cc.Vec2.ZERO) method to calculate the position of the node in the world coordinate system.

Then, use the setParent(newParent) method to set the node as the new parent node.

Finally, use convertToNodeSpaceAR(worldPosition) to convert the previously calculated world coordinate position to the local coordinates of the new parent node, and set the node's position through the setPosition() method to keep the absolute position unchanged.

Guess you like

Origin blog.csdn.net/weixin_41093846/article/details/131391398