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:

  1. I draw on JPanel in the method paint(Graphics gr)
  2. Using Graphics2D
Author: Roman C, 2021-01-20

1 answers

  1. Math.atan requires the relation y/x, but this is not so important, because see below

  2. Math.atan you need to replace it with Math.atan2(vy, vx) to get the angle in the entire range

  3. The result Math.atan/atan2 is already in radians, no need to convert yet if rotate 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)
 2
Author: MBo, 2021-01-20 17:07:56