0

I'm trying to create a method which rotates a point around another point in Java for a Asteroids clone that I want to make.Right now I have 2 Point instances called point and center.The code for my method is this:

public void Rotate(double angle){
       double a; 
       int x,y,distance;
       distance=30;
       a=Math.atan2((int)(point.getX()-center.getX()),(int)(point.getY()-center.getY()));
       a=a+angle;
       x=(int)(Math.cos(a)*distance);
       y=(int)(Math.sin(a)*distance);
       point.setLocation(x,y);   
}

And the code for my gameloop is this:

while (true){
      game.Rotate(10);
      game.repaint();
      Thread.sleep(10);
}

The problem is that the distance between the point and the center increases or decreases and I don't know why.Can somebody please tell me what's wrong?

EDIT [PROBLEM SOLVED]: For anyone interested here is how I solved the problem using the help that I got from the answers below: First, the Rotate function:

public void Rotate(double angle){
    double x,y;
    double distance=60;
    x=Math.round(center.getX() + (Math.cos(Math.toRadians(angle))*distance));
    y=Math.round(center.getY() + (Math.sin(Math.toRadians(angle))*distance));
    point.setLocation(x,y);
}

Then I made another method called move:

public void move(){
    angle+=2;
    if(angle>360){
        angle=0;
    }
    Rotate(angle);
}

And this is the game loop code:

while(true){
        main.move();
        main.repaint();
        Thread.sleep(10);
    }

Thanks again for your support.

Paul Iancu
  • 19
  • 1

2 Answers2

0

You need to realize affine trnsformation of 2D space. There is example how you can made it with java AffineTransform class. But if you don't want to do it though java Graphics there is algorithm in three steps:

  1. place object at center of rotation:

    x1=x-centerX;

    y1=y-centerY;

  2. rotate object on angle alpha(in radians):

    x2=x1*Math.cos(alpha)+y1*Math.sin(alpha);

    y2=x1*Math.sin(alpha)-y1.Math.cos(alpha);

  3. return object at it place:

    x3=x2+centerX;

    y3=y2+centerY;

This operations can be simply converts into matrix, and then you can use matrix algebra for your purpose.

0

You rotate point around coordinate origin. To rotate it about center, use

  x=center.getX() + (int)(Math.cos(a)*distance);
  y=center.getY() + (int)(Math.sin(a)*distance);
MBo
  • 77,366
  • 5
  • 53
  • 86