通过计算重复赋值

Repetitive value assignment with computation

我有一些不满意的 TS 代码。我正在做同样的事情三遍。这怎么可能更干净?

一个位置对象有一个 x、y 和 z 轴,可以用 position.x = ... 设置,或者用 position.set(x,y,z) 给它所有的值。

我可以使用一种遍历所有值并根据某些计算分配新值的映射函数吗?

private moveTowardsCamera(camera: THREE.Camera) {
        this.children.forEach((child: Asteroid) => {
            child.position.set(
                child.position.x += (camera.position.x - child.position.x) * this.speed,
                child.position.y += (camera.position.y - child.position.y) * this.speed,
                child.position.z += (camera.position.z - child.position.z) * this.speed  
            );
            child.rotation.set(
                child.rotation.x += this.rotationIncrement,
                child.rotation.y += this.rotationIncrement,
                child.rotation.z += this.rotationIncrement
            );
        });
    }

您可以遍历 ['x', 'y', 'z'] 的数组,映射它,并将其分散到不同的 .set 调用中:

// make sure to use `as const` here so the type doesn't get widened to Array<string>
const dims = ['x', 'y', 'z'] as const;
private moveTowardsCamera(camera: THREE.Camera) {
    this.children.forEach((child: Asteroid) => {
        child.position.set(
            ...(dims.map(dim => 
                child.position[dim] + (camera.position[dim] - child.position[dim]) * this.speed
            ) as [number, number, number])
        );
        child.rotation.set(
            ...(dims.map(dim => 
                child.rotation[dim] + this.rotationIncrement
            ) as [number, number, number])
        );
    });
}

很确定您应该使用新向量值调用 .set 方法,而不是在调用 [=12= 的同时重新分配 child.positionchild.rotation 值].