'How can I rotate a shape and have it move in the same direction that it is facing in Java?
I am rotating a shape in Java using g2D.rotate(Math.toRadians(rotationDegrees), x, y) where the x and the y are the axis that I want the shape to be rotating along. When I try to move the shape with a key listener, the shape still moves up, down, left, and right instead of moving according to the angle that it is facing. Is there any way that I can rotate a shape and have it move in the same direction that it is facing?

Solution 1:[1]
You need to do a little bit of trigonometry before you change your x and y values. Maintain a variable angle which stores the total amount that your shape has rotated from its initial position.
Now suppose you've got variables xChange and yChange that represent the desired change in x and y, but in the reference frame of the shape, not of the frame. Then instead of writing x += xChange; you'd write
x += (xChange * Math.cos(angle) + yChange * Math.sin(angle));
and instead of writing y += yChange; you'd write
y += (yChange * Math.cos(angle) - xChange * Math.sin(angle));
This assumes that angle is stored in radians, not degrees. You may also need to experiment with the + and - signs, depending on whether you're measuring y from top to bottom or bottom to top.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dawood ibn Kareem |
