Home > Mobile >  How to move an angle closer to another angle?
How to move an angle closer to another angle?

Time:01-11

If I have an angle theta (radians), a small angle delta (radians) and a target angle theta prime (radians), how can I increment/decrement theta by delta such that it would move closer to the angle theta prime? The goal is to push it closer and eventually reach and equal theta prime (but not go past it). It should work for negative radians or radians that are above Math.PI or lower than -Math.PI.

something like this

function MoveTheta(theta, delta, theta_prime) {
    // magic to move theta by at most delta closer to theta_prime
    return new_theta_value;
}

I would keep calling MoveTheta until MoveTheta equals theta_prime. How could this be written?

CodePudding user response:

function MoveTheta(theta, delta, theta_prime) {
    // find the distance between theta and theta_prime
    var diff = theta_prime - theta;
    
    // find the number of times you need to add/subtract delta to theta in order
    // to get to theta_prime (without passing theta_prime)
    var deltas = Math.floor(diff / delta);
    
    var new_theta_value = theta   deltas * delta;
    return new_theta_value;
}

Is this what you're looking for?

CodePudding user response:

What about:

    function move(theta, delta, theta_prime) {

        const diff = theta_prime - theta;

        return Math.abs(diff) > delta ? tetha   Math.sign(diff) * delta : tetha_prime;
    }

CodePudding user response:

Unless you don't care about usage of trig. functions, try the next approach (should solve problems with transition over zero, choose shortest direction etc):

rot = atan2(cos(th)*sin(th_pr)-cos(th_pr)*sin(th), 
            cos(th)*cos(th_pr) sin(th_pr)*sin(th))
if rot >= 0 
      new_th = th   min(delta, rot)     
else
      new_th = th   max(-delta, rot)     
  •  Tags:  
  • Related