Si tengo un ángulo theta (radianes), un ángulo pequeño delta (radianes) y un ángulo objetivo theta prime (radianes), ¿cómo puedo incrementar/disminuir theta por delta de modo que se acerque al ángulo theta prime ? El objetivo es empujarlo más cerca y eventualmente alcanzar e igualar theta prime (pero no pasarlo). Debería funcionar para radianes negativos o radianes que estén por encima de Math.PI o por debajo de -Math.PI.
algo como esto
function MoveTheta(theta, delta, theta_prime) { // magic to move theta by at most delta closer to theta_prime return new_theta_value; }Seguiría llamando a MoveTheta hasta que MoveTheta sea igual a theta_prime. ¿Cómo se podría escribir esto?
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; }¿Es esto lo que estás buscando?
Puedes probar la siguiente solución:
Primero evalúe la distancia desde el ángulo objetivo. Luego, si la distancia es menor que el paso, devuelva el ángulo objetivo o el ángulo original más el paso multiplicado por el signo de la diferencia para tener en cuenta la dirección de la rotación.
function move( theta, // the original angle delta, // the step theta_prime // the target angle ) { const diff = theta_prime - theta; return Math.abs(diff) > delta ? tetha + Math.sign(diff) * delta : tetha_prime; }si el resultado de este método es igual al ángulo objetivo, el procedimiento está completo.
function move(theta, delta, theta_prime) { const diff = theta_prime - theta; return Math.abs(diff) > delta ? theta + Math.sign(diff) * delta : tetha_prime; } let theta = 75; const delta = 4; const theta_prime = 32; while (theta != theta_prime) { theta = move(theta, delta, theta_prime); console.log(theta); } console.log("done");A menos que no te importe el uso de trig. funciones, intente el siguiente enfoque (debería resolver los problemas con la transición sobre cero, elija la dirección más corta, 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)