dev-cyprium
dev-cyprium

Reputation: 768

Java AWT rotating ball

Oh boy, trigonometry is so hard! I kinda need some help, It's a simple program that is supposed to rotate a ball around the center of the screen... Here is my code:

import java.awt.*;

import javax.swing.*;


public class Window {
private int x;
private int y;
private int R = 30;
private double alpha = 0;

private final int SPEED = 1;
private final Color COLOR = Color.red;

public static void main(String[] args) {    
    new Window().buildWindow();
}

public void buildWindow() {
    JFrame frame = new JFrame("Rotation");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(800,600);
    frame.setVisible(true);
    frame.add(new DrawPanel());
    while(true) {
        try {
            Thread.sleep(60);
            alpha += SPEED;
            frame.repaint();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

@SuppressWarnings("serial")
class DrawPanel extends JPanel {


    @Override
    public void paintComponent(Graphics g) {
        g.setColor(Color.blue);
        Font font = new Font("Arial",Font.PLAIN,12);
        g.setFont(font);
        g.drawString(String.format("Angle: %.2f ", alpha), 0, 12);

        g.setColor(Color.black);
        g.drawLine(this.getWidth()/2,0, this.getWidth()/2, this.getHeight());
        g.drawLine(0, this.getHeight()/2, this.getWidth(), this.getHeight()/2);

        x = (int) ((this.getWidth() / 2 - R / 2 ) + Math.round((R + 20) * Math.sin(alpha)));
        y = (int) ((this.getHeight() / 2 - R / 2 ) + Math.round((R + 20) * Math.cos(alpha)));

        g.setColor(COLOR);
        g.fillOval(x, y, R, R);
    }
}
}

This code looks like it's working, but then I've printed Angle[alpha] information to the screen. And when I comment out the alpha+=SPEED and enter the angle manually it does not look like it's working.The angle on the screen doses not correspond to that angle alpha. So I need suggestions. What should I change? Is my trigonometry wrong? etc...

Upvotes: 1

Views: 1329

Answers (1)

Grodriguez
Grodriguez

Reputation: 21995

Three things to note here:

  1. I assume your alpha variable is in degrees since you are adding 20 in each step. However the Math.sin() and Math.cos() methods expect an angle in radians.
  2. Normally 0 deg (or 0 rads) is represented at the "3 o'clock" position. For this you need to switch the sin and cos calls.
  3. Reverse the sign in the y equation to account for the fact that y coordinates start at the top of the screen and increase downwards

With these modifications, your code will work as you expect:

double rads = (alpha * Math.PI) / 180F;
x = (int) ((this.getWidth() / 2 - R / 2 ) + Math.round((R + 20) * Math.cos(rads)));
y = (int) ((this.getHeight() / 2 - R / 2 ) - Math.round((R + 20) * Math.sin(rads)));

Upvotes: 2

Related Questions