0

I am creating a flights radar simulator in Java, for a class project.

So far, I've been able to show many small airplane images moving across the radar with a given direction and different speed.

My problem is how can i rotate each airplane image to follow its direction in the radar. Radar

The line shows the direction where the plane is moving and should be pointing.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
sandiego
  • 151
  • 1
  • 4
  • 10

2 Answers2

1

There are a few ways to do this in Java. AffineTransform works, but I found that I couldn't easily resize images to handle non-90-degree rotations. The solution I ended up implementing is below. Angles in radians.

public static BufferedImage rotate(BufferedImage image, double angle) {
    double sin = Math.abs(Math.sin(angle)), cos = Math.abs(Math.cos(angle));
    int w = image.getWidth();
    int h = image.getHeight();
    int newW = (int) Math.floor(w * cos + h * sin);
    int newH = (int) Math.floor(h * cos + w * sin);
    GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment()
                                                  .getDefaultScreenDevice()
                                                  .getDefaultConfiguration();

    BufferedImage result = gc.createCompatibleImage(newW, newH, Transparency.TRANSLUCENT);
    Graphics2D g = result.createGraphics();
    g.translate((newW - w) / 2, (newH - h) / 2);
    g.rotate(angle, w/2, h/2);
    g.drawRenderedImage(image, null);
    g.dispose();
    return result;
}
PattimusPrime
  • 867
  • 8
  • 21
  • In the case of the above airplanes, that's bound to happen. Each airplane is only a few pixels wide, so the pixel rounding will be noticeable. Three fixes that come to mind: 1. Use a bigger airplane image, rotate before scaling, and use those instead of rotating, 2. Make a few sprites of the same plane at different angles, 3. Use vector instead of raster images (ie. svg) and a library like Batik. The third idea would be more difficult to implement, but result in better graphics. – PattimusPrime Sep 03 '13 at 03:16
0

I assume you are using Java2d, so you should take a look on AffineTransform class

Mac70
  • 320
  • 5
  • 15