I wish to make a turret in a 2d game, which should rotate smoothly to the angle of the mouse. I came up with two solutions but neither are satifactory. The first:
currentRot = targetRot; // Produces snapping + doesn't look realistic
The second, inspired from Smoothly rotate turret and retain accuracy :
if (currentRot < targetRot)
{
currentRot += 2;
if(currentRot > targetRot)
{
currentRot = targetRot;
}
}
if (currentRot > targetRot)
{
currentRot -= 2;
if(currentRot < targetRot)
{
currentRot = targetRot;
}
}
However, the second approach doesn't rotate in the optimal direction all the time. The code doesn't "know" which way to rotate is shorter. I cannot use libraries, and I think quaternions are overkill, so I'm unsure how to solve this problem. Also, is there a third approach that is simpler/better?
Other info: targetRot is from 0°-360°
I found a cheesed solution, after a long time! This was oddly challenging. I still feel like my solution was sub-optimal though
It just checks which way is shorter
var dp = /*world distance from currentRot to targetRot+5 on unitcircle*/
var dp = /*world distance from currentRot to targetRot-5 on unitcircle*/
if (currentRot < targetRot) {
currentRot += rate * (dp < dm ? -1 : 1);
if (currentRot > targetRot) {
currentRot = targetRot;
}
}
if (currentRot > targetRot) {
currentRot -= rate * (dp < dm ? 1 : -1);
if(currentRot < targetRot) {
currentRot = targetRot;
}
}
and also this line fixed some bugs
if (currentRot < 0) {currentRot += 360;}