Hi everyone,
In my current game I intend for the player controlled character to turn to face the mouse and keyboard keys move them. My first implementation was to have them face it at all times which was no problem.
Next I wanted to have it turn at a specified rate toward the mouse.
This came up with some new issues. When the mouse crossed over the 180’ to -180’ range it would start turning the other way.
I did end up solving this though
double delta_x = mouse.x - position.x;
double delta_y = mouse.y - position.y;
double angle = Math.toDegrees(Math.atan2(delta_y, delta_x));
double difference = angle - direction;
while (difference < -180) difference += 360;
while (difference > 180) difference -= 360;
if(difference < 0)
direction -= turnRate;
else
direction += turnRate;
if(mouseLast.equals(mouse)) {
if(Math.abs(difference) < turnRate) {
direction = angle;
}
}
This took me a while to find so if anyone else had this issue I hope this helps but my question is to do with the last if statement. Without it, the character would jump around back and forward because its pretty much impossible to ‘land’ on the angle to face with a specified turn rate.
First I just had the ‘if angle difference is less than turn rate, set it to the angle’ This was ok and got rid of any jagged movement but on a character with a low turn rate, you could move the mouse slowly and it would keep snapping to that angle and you could turn it WAYYY faster than it could on its own.
Now with the current mouse check against the last to see if its moving it wont ‘cheat’ but now for fast turning characters on slow mouse movements it will jump back and foward around the target point.
So is this a problem that can be fixed or will it always be a trade off between the two. Or is there any other trigonometric techniques that will help?