怎么用代码实现 子节点显示的内容 相对父节点 是居中显示的。

子节点的锚点设为0.5,位置设为cc.v2(0,0)

原来写一个需要居中的节点node.setPosition(parent.width/2,parent.height/2),

现在需要写的

node.setPosition(parent.width*(0.5-parent.anchorX),parent.height*(0.5-parent.anchorY))。

现在的很容易忘记写现在的这种写法 一旦父节点的锚点不在中心点,位置就不会居中。

参考链接:https://www.jianshu.com/p/99c52ee470d7

相关问题 位置系统对程序员来说极度不友好

export const contentToCenter = (node: cc.Node) => {
    let minX: number = null;
    let maxX: number = null;
    node.children.forEach((item) => {
        if (minX == null || minX > item.x - (item.anchorX * item.width)) {
            minX = item.x - (item.anchorX * item.width);
        }
        if (maxX == null || maxX < item.x + ((1 - item.anchorX) * item.width)) {
            maxX = item.x + ((1 - item.anchorX) * item.width);
        }
    });
    const tt = minX + (maxX - minX) / 2;
    node.children.forEach((item) => {
        item.x -= tt;
    });
};