在圆上绘制点

时间:2015-10-14 22:01:09

标签: java rotation trigonometry

我在java中玩游戏并试图创建自己的点类版本:

public class Location {
    public double x, y;

    public Location(double x, double y) {
        this.x = x;
        this.y = y;
    }

    public double dist(Location location) {
        return Math.sqrt(Math.pow(location.x - x, 2) + Math.pow(location.y - y, 2));
    }

    //Rotates the point the amount in angle around the point center
    public void rotate(Location center, double angle) {
        //Also tried this
        /*double current = Math.atan2(center.y - y, center.x - x);
        x = center.x + (Math.cos(current + angle) * dist(center));
        y = center.y + (Math.sin(current + angle) * dist(center));*/
        //Current code
        x = center.x + (Math.cos(angle) * dist(center));
        y = center.y + (Math.sin(angle) * dist(center));
    }
}

但是,无论我尝试什么,rotate()函数返回的数据都略有偏差。这个函数不是一个完美的圆形,而是输出一个奇怪的放气形状。

public class Circle {

    //Should output circle
    public static void main(String[] args) {
        for (int i = 0; i < 18; i++) {
            Location point = new Location(100, 100);
            point.rotate(new Location(200, 200), Math.toRadians(i * 20));
            System.out.print("(" + point.x + ", " + point.y + ")");
        }
    }
}

当我将这些坐标输出到this plotting site时,这是我得到的图像:Weird shape that isn't a circle

我的数学与Java: Plotting points uniformly on a circle using Graphics2d相同,所以我不知道发生了什么。

1 个答案:

答案 0 :(得分:2)

计算dist(center)一次,将其存储在变量中,然后在更新xy时使用该变量:

double d = dist(center);
x = center.x + (Math.cos(angle) * d);
y = center.y + (Math.sin(angle) * d);

dist(center)取决于x,因此在计算x的新值时,在更新y后会得到不同的值。