Search code examples
three.js

Three JS - Access ArrowHelper direction?


Suppose I create an arrow helper, e.g. something like:

const arrowPosition = new THREE.Vector3(0, 0, 0);
const arrowPosition = new THREE.Vector3(2, -2, 0);

arrowDirection.subVectors( scene.position, new THREE.Vector3(1, 1, 1)).normalize();

arrow = new THREE.ArrowHelper( arrowDirection, arrowPosition, arrowLength, 0xffff00, arrowHeadLength, arrowHeadWidth);

After creating it, how do I access its direction?


Solution

  • In short, I'm not sure there is an easy way to access the direction, at least in a vector3 format. The value dir used in the ArrowHelper constructor (as described in the docs) is never assigned directly to a vector property of ArrowHelper or the Object3D parent class, but is instead used to set the quaternion property of the ArrowHelper, inherited from the parent class.

    See the code snippet below from the helper source code:

    setDirection(dir) {
      // dir is assumed to be normalized
    
      if (dir.y > 0.99999) {
        this.quaternion.set(0, 0, 0, 1);
    
      } else if (dir.y < - 0.99999) {
        this.quaternion.set(1, 0, 0, 0);
    
      } else {
        _axis.set(dir.z, 0, - dir.x).normalize();
        const radians = Math.acos(dir.y);
        this.quaternion.setFromAxisAngle(_axis, radians);
      }
    }
    

    As listed in the Object3D docs, the quaternion describes the helper's rotation (quaternion docs). A better discussion on the math might be found on this unity forum, but to get the vector direction you'll need to use the quaternion field

    Hope this helps and if someone can improve this explanation please do, my experience with Eulers and quaternions is limited