Sign in to follow this  
Patriarch K

Getting my object to rotate and move 'ala Asteroid

Recommended Posts

I'm trying to work with rotation and movement but I have a problem that I can't really solve. When I rotate from the starting point then it works fine and a can rotate at any direction and then move to that direction. But when I try to rotate from my new position, then the object moves around the "starting point" (g2d.Translate). I try to somehow update the root position to my new position, but it doesn't really work. Try it out and see. Maybe I don't use the easiest method for this, but I feel that I'm close with this method and I want to use it. Here is my code:


import java.applet.AudioClip;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Level1 extends JPanel implements ActionListener{

	Image i;
	Graphics doubleG;
	ImageIcon keyIcon = new ImageIcon(this.getClass().getResource("img/BubbleSpeed.gif"));
	Image key = keyIcon.getImage();
	ImageIcon backgroundIcon = new ImageIcon(this.getClass().getResource("img/background3.png"));
	Image background = backgroundIcon.getImage();
	URL music = null;
	AudioClip musicSound;
	int x = 400;
	int y = 400;
	int x2 = 400;
	int y2 = 400;
	double dx;
	double dy;
	int rotate;
	int center = 20;
	Timer tim;

		tim = new Timer(25, this);

	public void move(){
		y += dy;
		x += dx;

	public void update(Graphics g) {
		if(i == null){
			i = createImage(this.getWidth(), this.getHeight());
			doubleG = i.getGraphics();
		doubleG.fillRect(0, 0, this.getWidth(), this.getHeight());
		g.drawImage(i, 0, 0, this);

	public void paintComponent(Graphics g){
		Graphics2D g2d = (Graphics2D) g;
		g2d.drawImage(background, 0, 0, null);
		g2d.rotate(Math.toRadians(rotate), x2,y2);
		g2d.drawImage(key, x-center, y-center, null);

	public void actionPerformed(ActionEvent arg0) {

	KeyListener k = new KeyAdapter(){
		public void keyPressed(KeyEvent e) {

			if(e.getKeyCode() == KeyEvent.VK_X){	
			if(e.getKeyCode() == KeyEvent.VK_Z){	
			if(e.getKeyCode() == KeyEvent.VK_W){	
				dy = -10;
			if(e.getKeyCode() == KeyEvent.VK_S){	
				dy = 10;
		public void keyReleased(KeyEvent e) {
			dx = 0;
			dy = 0;
			x2 = x;
			y2 = y;



Edited by Patriarch K

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this