Search code examples
javascriptmaththree.jsradians

Calculate target range on circle Three.js


I have a Math problem I'm struggling with.

I have a particular radian I want to point the camera at (camera.rotation.y). I want to tell the user if they need to pan left or right to get to that radian, with a tolerance of PI/4.

I've normalised the pan number by getting the camera + dolly rotation

function getCurrentPan(){
    return dolly.rotation.y + camera.rotation.y > 0
        ? (dolly.rotation.y + camera.rotation.y)%Math.PI
        : ((dolly.rotation.y + camera.rotation.y)%Math.PI) + Math.PI;
}

So it's always between 0 and PI.

I'd planned on working out the range which I can check against to see if the user needs to pan left or right to get to that radian. Trying this code:

      point.leftRange = {};
        point.leftRange.min = point.pan - range > 0 ? point.pan - range : Math.PI - point.pan - range;
        point.leftRange.max = point.leftRange.min - Math.PI/2 - range > 0 ? (point.pan - range)%Math.PI : (Math.PI - (point.leftRange.min - Math.PI/2 - range))% Math.PI;

        console.log(point.leftRange);

        point.rightRange = {};
        point.rightRange.min = (point.pan + range) % Math.PI;
        point.rightRange.max = (point.rightRange.min + (Math.PI/2 - range)) % Math.PI;

        console.log(point.rightRange);

Which is giving me something like

  • point.pan 1.464308692701496
  • left.min 1.071609611002772
  • left.max 0.8918857974908487
  • right.min 1.8570077744002202
  • right.max 3.0351050194963927

Another approach I've tried is

             var opp = (point.pan - Math.PI/2)%Math.PI;
                opp = opp > 0 ? opp : Math.PI - opp;

                if(getCurrentPan() > point.pan && getCurrentPan() < opp)
                     console.log('greater');
                else if(getCurrentPan() < point.pan && getCurrentPan() > opp)
                     console.log('less');

Which again won't take into account if the pan is like 0.5 and left range is 3 etc (other side of PI).

Sorry I'm not explaining this well but if anyone can point me the right direction I'd appreciate it!


Solution

  • This is overengineered. if you want to figure out whether a target is to the left or right of the camera, you do this:

    d = camera.getworlddirection();
    diff = target.position - camera.position;
    theta = atan2(diff.x,diff.z) - atan2(d.x,d.z);
    

    this is the angle between where your camera is looking vs where the object is in relation to the camera.

    so:

    if(abs(theta) < someThreshold){
      if(theta > 0){
        //its to the right
      }
      else{
       //its to the left
      }
    }