向量运算的一个问题,不知道算不算是bug

  • Creator 版本: 3.3.0

在将2.4.5的项目升到3.3.0的之后,碰到一个bug,排查了很久,终于找到了问题所在,先贴代码

enum DirType {

none,

left,

right

}

@ccclass(‘Test’)

export class Test extends Component {

onLoad() {

    systemEvent.on(SystemEvent.EventType.KEY_UP, this.onKeyUp, this);

}

onDisable() {

    systemEvent.off(SystemEvent.EventType.KEY_UP, this.onKeyUp, this);

}

private getDirType(dir: Vec3) {

    var dirType = dir.normalize().x > 0 ? DirType.right : DirType.left;

    return dirType;

}

private onKeyUp(event: EventKeyboard) {

    switch (event.keyCode) {

        case KeyCode.KEY_A:

            var movePos = new Vec3(100, 100, 0);

            error("movePos=", movePos);

            var currPos = this.node.getComponent(UITransformComponent).convertToWorldSpaceAR(Vec3.ZERO);

            var dir = movePos.subtract(currPos);

            error("movePos=", movePos);

            var dirType: DirType = this.getDirType(dir.normalize());

            error("movePos=", movePos);

            break;

    }

}

}
再看运行结果:


问题的根源在于subtract这个函数,为什么我用当前向量减去一个向量,当前向量的值却改变了呢,难道不应该是用一个新的向量去接受它们两个运算之后的结果,然后返回这个新的向量吗。我吐了

还有normalize()这个方法,都将自身的值给改了

2.x normalize就是自己向量归一化

unity是返回一个新的向量

https://github.com/cocos-creator/engine/blob/v3.3.0/cocos/core/math/vec3.ts#L110

他这个有3个参数,第一个参数就是作为修改后输出的呀

3.x是这样的,2.x有个subSelf啥的

对 我也记得有个self什么的找不到了,原来是2.x的

我看了下,这个方法是Vec3的静态方法,确实能解决这个问题

2.x的就是sub,