Drawing an image rotated in the direction of movement | Graphics | Graphics2D
It is necessary to draw the image rotated in the direction of movement (the rotation should be relative to the center of the image):
Example:
I know the speed of x and y, and the position of the image(x,y), and the size of the image(width and height), as well as the size of the field on which I draw
I tried this way:
Graphics2D g = (Graphics2D) gr;
g.rotate(Math.toRadians(Math.atan(vx/vy))); // vx,vy - скорость по x и y
g.fillRect((int)(x-w/2), (int) (y-h/2), w, h); // Это я потом заменю на картинку
But the image is NOT rotated relative to the center and the rotation is incorrect
Details:
- I draw on JPanel in the method
paint(Graphics gr)
- Using Graphics2D
1 answers
-
Math.atan
requires the relationy/x
, but this is not so important, because see below -
Math.atan
you need to replace it withMath.atan2(vy, vx)
to get the angle in the entire range -
The result
Math.atan/atan2
is already in radians, no need to convert yet ifrotate
requires radians
For rotation relative to a certain point (cx, cy)
, the affine transformation matrix is constructed as follows:
перенос на (-cx, -cy)
поворот
перенос на (cx, cy)
In Graphics2D I see an overlap for this method:
rotate(double theta, double x, double y)