Conversion between cocosCreator node coordinates and world coordinates

Problem description: Elements under different nodes on the same layer move.

 There are two nodes A and B on the layer C, now I want to move a temporarily created node under A to B

 

At this time, the first thought is to get the coordinates of the two created nodes, and then cc.Move

 

But the actual effect is not like this, the elements don't know where to move?

Because the coordinates of nodes are relative. It is to create a new node under A, and its coordinates are cc.v2(0,0);

Transform world coordinates

The overall idea is

1、获取双方的世界坐标

2、转换为统一的节点的相对坐标

3、设置坐标

 The following is the coordinate conversion code

/**
 * 得到一个节点的世界坐标
 * node的原点在中心
 * @param {*} node 
 */
function localConvertWorldPointAR(node) {
    if (node) {
        return node.convertToWorldSpaceAR(cc.v2(0, 0));
    }
    return null;
}
 
/**
 * 得到一个节点的世界坐标
 * node的原点在左下边
 * @param {*} node 
 */
function localConvertWorldPoint(node) {
    if (node) {
        return node.convertToWorldSpace(cc.v2(0, 0));
    }
    return null;
}
 
/**
 * 把一个世界坐标的点,转换到某个节点下的坐标
 * 原点在node中心
 * @param {*} node 
 * @param {*} worldPoint 
 */
function worldConvertLocalPointAR(node, worldPoint) {
    if (node) {
        return node.convertToNodeSpaceAR(worldPoint);
    }
    return null;
}
 
/**
 * 把一个世界坐标的点,转换到某个节点下的坐标
 * 原点在node左下角
 * @param {*} node 
 * @param {*} worldPoint 
 */
function worldConvertLocalPoint(node, worldPoint) {
    if (node) {
        return node.convertToNodeSpace(worldPoint);
    }
    return null;
}
/**
 *  * 把一个节点的本地坐标转到另一个节点的本地坐标下
 * @param {*} node 
 * @param {*} targetNode 
 */
function convetOtherNodeSpace(node, targetNode) {
    if (!node || !targetNode) {
        return null;
    }
    //先转成世界坐标
    let worldPoint = localConvertWorldPoint(node);
    return worldConvertLocalPoint(targetNode, worldPoint);
}
 
/**
 *  * 把一个节点的本地坐标转到另一个节点的本地坐标下
 * @param {*} node 
 * @param {*} targetNode 
 */
function convetOtherNodeSpaceAR(node, targetNode) {
    if (!node || !targetNode) {
        return null;
    }
    //先转成世界坐标
    let worldPoint = localConvertWorldPointAR(node);
    return worldConvertLocalPointAR(targetNode, worldPoint);
}

 

Guess you like

Origin blog.csdn.net/huanghuipost/article/details/102825429