Search code examples
javaswingrotationrotateanimation

360 degree movement example in java


is it possible to simply make 360 degree movement in java(swing) without any game engine? all I have is this attempt:

public class Game extends JPanel implements Runnable {

    int x = 300;
    int y = 500;
    float angle = 30;
    Game game;

    public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.add(new Game());
    frame.setSize(600, 600);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public Game() { 
    setSize(600, 600);

    Thread thread = new Thread(this);
    thread.start();
    }

    @Override
    public void paint(Graphics g) {
    g.setColor(Color.WHITE);
    g.drawRect(0, 0, 600, 600);
    g.setColor(Color.CYAN);
    g.fillOval(x, y, 10, 10);
    g.dispose();
    }

    @Override
    public void run() {
    while(true) {
        angle += -0.1;
        x += Math.sin(angle);
        y--;
        repaint();
        try {
        Thread.sleep(50);
        } catch (InterruptedException ex) {}
    }
    }

}

as you can see in following picture, I don't know how to handle movement rotating, this is the output:

image http://screenshot.cz/GOXE3/mvm.jpg


Solution

  • Change a few lines...

    int basex = 300;   // midpoint of the circle
    int basey = 400;
    int radius = 100;  // radius
    int x;
    int y;
    float angle = 0;  // Angles in radians, NOT degrees!
    
    public void run() {
      while(true) {
        angle += 0.01;
        x  = (int)(basex + radius*Math.cos(angle));
        y  = (int)(basey - radius*Math.sin(angle));
        repaint();
        try {
            Thread.sleep(50);
        } catch (InterruptedException ex) {}
      }
    }
    

    Not sure what you were trying to code there, but this is the correct formula for a circular movement.