从中心随机生成点

时间:2014-06-01 02:21:03

标签: java

我正试图用初始点的随机位置创建一组点。 不幸的是,几乎所有生成的点都位于左上角。我的计算中有错误吗?

private void makePath() {

    int r = 25;
    Random rand = new Random();
    double angle = Math.toRadians(rand.nextInt(361));
    int nx = (int) (x + r * Math.cos(angle));
    int ny = (int) (y - r * Math.sin(angle));
    path.add(new Point2D(nx, ny));

}

1 个答案:

答案 0 :(得分:0)

对于值,请尝试使用:

int nx = (int) (x + r * Math.cos(angle));
int ny = (int) (y + r * Math.sin(angle));

改为使用y + r * ...。这来自我写的一个完全相同的方法:

/**
 * Generates a new point within a circular radius from
 * the given <tt>x</tt> and <tt>y</tt> coordinates. This
 * is done by generating a random offset along the
 * horizontal axis, then applying a rotation.
 *
 * @param seed The seed to generate the point from.
 * @param x    The x coordinate of the center of the
 *             circle.
 * @param y    The y coordinate of the center of the
 *             circle.
 * @return The newly generated point, within the
 * specified radius of the point <tt>(x, y)
 * </tt>.
 * @see ClusterGenerator#RADIUS
 */

private static Point makePoint(final Random seed, final int x, final int y) {
    final int offset = seed.nextInt(RADIUS);
    final double rotation = 2 * Math.PI * Math.random();
    final int x1 = (int) (Math.sin(rotation) * offset);
    final int y1 = (int) (Math.cos(rotation) * offset);
    return new Point(x + x1, y + y1);
}