Search code examples
javascript3dthree.jsmultiplayerdirection

How does Three.js store direction?


i'm writing a server for a game me and my friends are making. I want to keep the direction a certain player is looking at in a 3D plane in a variable. I was considering having it an object with two variables of radians, i.e vertical angle and horizontal angle. But my friend told me to store it the way Three.js stores it because it would make his life easier. Could anybody help me out here?


Solution

  • You should brush up on Math for Game Developers series: https://www.youtube.com/watch?v=sKCF8A3XGxQ&list=PLW3Zl3wyJwWOpdhYedlD-yCB7WQoHf-My&index=1

    Specifically, using vectors. You should store the orientation / facing angle of your characters or entities as a Vector3, or a 3 dimensional vector. In THREE.js, that's new THREE.Vector3( x, y, z )

    To get the direction of object A to object B, relative to A you would do:

    var direction = posB.clone().sub( posA )
    

    This clones position B so we don't mess it up by subtraction, and then immediately subtract it by A.

    However you'll notice how the vector now has some length. This is often undesirable in calculations, for example if you wanted to multiply this direction by something else say, a thrust force. In this case, we need to normalize the vector:

    direction.normalize()
    

    Now you can do fun stuff like:

    posA.add( direction.clone().multiplyScalar( 10.0 ) );
    

    This will move posA in the direction towards posB, 10 units of space.