Skip to content

Instantly share code, notes, and snippets.

@sye8
Last active May 12, 2022 18:57
Show Gist options
  • Save sye8/edba2dfda1645b37bfcf5b9bd9ce3a75 to your computer and use it in GitHub Desktop.
Save sye8/edba2dfda1645b37bfcf5b9bd9ce3a75 to your computer and use it in GitHub Desktop.
Java Rotating An Image - Graphics2D, KeyListener, Timer

Rotating an Image in Java, Animated

A common idea in video game development is a sprite, which is a 2D image used as a part of the graphics display. For example, Mario and coins are sprites in Super Mario.

If you are thinking about a space shooter, like Asteriod, then you probably need to think about how to rotate the ship, which could be an image.

Assuming that you have a JFrame with a JComponent for drawing set up and an Image of the sprite ready, we will begin.

Insert No Time for Caution by Hans Zimmer

1. Rotating an Image, without animation

In your JComponent extension's paintComponent(Graphics g), we will draw the sprite.

However, Graphics itself isn't quite enough: it can draw an image, but not rotating one. For this task, we will use Graphics2D which is more powerful than Graphics.

public void paintComponent(Graphics g){
    Graphics2D g2d = (g2d)g; // We will cast g to a Graphics2D object
    g2d.drawImage(sprite, spriteX, spriteY, null); // You probably know how to do that in Graphics already
}

And the output is nothing surprising:

screen shot 2018-12-05 at 00 06 38

Now, to rotate the image, say 30 degrees, we will add this line before g2d.drawImage():

g2d.rotate(Math.toRadians(30), centerX, centerY); //centerX and centerY is your center of rotation.

Voila!

screen shot 2018-12-04 at 23 38 21

2. Rotating, with animation

A tilted image is not that interesting, a spinning image sounds way more fun. No Time For Caution Intensifies

Well, to keep an image rotating, we will need a Timer and its corresponding ActionListener. We will add a variable called rotation and an inner class called TimerHandler:

@Override
public void actionPerformed(ActionEvent e) {
    if(rotation < 360){
        rotation += 5;
    }
	repaint();
}

This will update the rotation of the image for each loop of the timer, until we reach a full turn, and, well, repaint the sprite with the updated rotation. Effectively, this is an animation of our sprite rotating 360 degrees

3. Rotating, under your control

While Endurance spins out of control, we would like to steer our little sprite, using our keyboard.

Add a KeyListener extension to your class, and we will use keys A and D to steer our sprite.

Furthermore, we will add two booleans rotatingLeft and rotatingRight to keep track of our sprite's status.

private class KeyHandler implements KeyListener{

	@Override
	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub
		//Do nothing
	}

	@Override
	public void keyPressed(KeyEvent e) {			
		switch(e.getKeyCode()){
			case KeyEvent.VK_D:
				System.out.println("Rotating Right");
				rotatingRight = true;
				rotatingLeft = false;
				break;
			case KeyEvent.VK_A:
				System.out.println("Rotating Left");
				rotatingLeft = true;
				rotatingRight = false;
				break;
		}
	}

	@Override
	public void keyReleased(KeyEvent e) {
		switch(e.getKeyCode()){
			case KeyEvent.VK_D:
				System.out.println("Stop Rotating Right");
				rotatingRight = false;
				rotatingLeft = false;
				break;
			case KeyEvent.VK_A:
				System.out.println("Stop Rotating Left");
				rotatingLeft = false;
				rotatingRight = false;
				break;
		}
	}
}	

For our purposes, we will set the sprite to be spinning if a corresponding key is pressed and to stop spinning if a key is released.

As you noticed, this doesn't actually update our sprite's rotation. This is done in TimerHandler. Modify it to rotate according to the direction:

public void actionPerformed(ActionEvent e) {
	// TODO Auto-generated method stub
	if(rotatingLeft){
		rotation -= 5;
	}
	if(rotatingRight){
		rotation += 5;
	}
	repaint();
}

Now, go ahead add the KeyHandler to your JFrame, start the timer and steer our little ship!

ezgif-4-1927e8583323

Sifan Ye

@pratik28122001
Copy link

I tried to follow your steps but it doesn't works . It would be helpful if you would send me the full code please.
Kind regards

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment