1

I have some TS code that I'm not happy with. I'im doing three times the same thing. How could this be cleaner?

A position object has an x, y and z axis that can be set with position.x = ... or give it all the values with position.set(x,y,z).

Could I use a sort of map function that goes over all the values and assigns a new value based on some computation.

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
            );
        });
    }
Thhollev
  • 73
  • 1
  • 1
  • 10
  • What is the `.set` method? It looks extremely strange to be passing an argument *and* reassigning `child.position.#` in the same statement. Can you do, for example, `child.position.set( child.position.x + (camera.position.x - child.position.x) * this.speed`, will that work as well? – CertainPerformance Jan 21 '21 at 19:55
  • https://threejs.org/docs/index.html#api/en/math/Vector3 maybe I could use Vector3.fromArray in a way... – Thhollev Jan 21 '21 at 19:58

1 Answers1

1

You can iterate over an array of ['x', 'y', 'z'], map it, and spread it into the different .set calls:

// 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])
        );
    });
}

Pretty sure you should be calling the .set method with the new vector values instead of reassigning the child.position or child.rotation values at the same time that you call .set.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320