I have this code in my game loop:
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
if (aPress) {
rotate -= rotSpd;
rotate = rotate < 0 ? 360 + rotate : rotate;
}
if (dPress) {
rotate += rotSpd;
rotate = rotate > 360 ? rotate - 360 : rotate;
}
if (wPress) {
x += (rotate < 180 ? speed : -speed) * Math.abs(Math.sin(Math.toRadians(rotate)));
y += (rotate < 270 ? (rotate < 90 ? -speed : speed) : -speed) * Math.abs(Math.cos(Math.toRadians(rotate)));
}
if (sPress) {
x -= (rotate < 180 ? speed : -speed) * Math.abs(Math.sin(Math.toRadians(rotate)));
y -= (rotate < 270 ? (rotate < 90 ? -speed : speed) : -speed) * Math.abs(Math.cos(Math.toRadians(rotate)));
}
repaint();
try {
Thread.sleep(20);
} catch (InterruptedException annoyingUncheckedException) {}
}
}
}).start();
It does what it should do: when you press A, it turns counterclockwise. When you press D, it turns clockwise. When you press W, it goes forward, and when you press S, it goes backwards. However, if I hold W and D, at first it goes in a circle like it should, but it slowly starts going in the direction of the top left corner. How can I fix this?
First of all, I would make use of the modulo operator, for a better understanding of the code overall (and perhaps it is also less error-prone).
Concerning your issue, I made a quick jsFiddle to see if I could reproduce the problem but I cannot, so I guess this is related to the way key press (down/up/hold) events are handled. Perhaps you can try to log the set of pressed keys on each iteration and try to see If there is some kind of inconsistency.
NB : W/A/S/D keys have been replaced by UP/DOWN/LEFT/RIGHT in my jsFiddle to minimize keyboard layout issues. I also refactored the code of the loop to reflect my logic and the SJuan76 answer.