java - 将对象均匀地分布在一条线上

发布于 2024-10-05 16:06:19 字数 690 浏览 2 评论 0原文

我正在由这段代码创建的窗口中的一行上创建对象:

void createTurtles() {
     int nrTurtles = Keyboard.nextInt("Set amount of turtles: ");
     w = new GraphicsWindow(500, 300);
     drawLinez();
     for (int k = 1; k <= nrTurtles; k++) {
        Turtle t = new Turtle(w, 50, 50 + k*10);
        t.right(90);
        t.setSpeed(100);
        t.penDown();
        turtles.add(t);
     }
}

此代码行:

        Turtle t = new Turtle(w, 50, 50 + k*10);

一次创建一只乌龟。现在我已经设置海龟的 Y 坐标为 50,X 坐标为 50+k*10。这是因为该线从 X 坐标 50 开始,到 X 坐标 250 停止。

现在我想要的是,根据创建的海龟数量(用户输入),我希望海龟分布在这条线上均匀。怎么做呢?它与我写的那行有关,可能与 k 值或 10 有关。

该行如图所示(请参见下面的链接),它是红线,即创建海龟的数量。

I am creating objects on a line in a window created by this piece of code:

void createTurtles() {
     int nrTurtles = Keyboard.nextInt("Set amount of turtles: ");
     w = new GraphicsWindow(500, 300);
     drawLinez();
     for (int k = 1; k <= nrTurtles; k++) {
        Turtle t = new Turtle(w, 50, 50 + k*10);
        t.right(90);
        t.setSpeed(100);
        t.penDown();
        turtles.add(t);
     }
}

This codeline:

        Turtle t = new Turtle(w, 50, 50 + k*10);

Creates one turtle at the time. Right now i have set that the turtles will have the Y coordinat of 50, and the X coordinat of 50+k*10. This is because the line starts at the X coordinat of 50 and stops at the X coordinat of 250.

Now what i want is, based on the nr of turtles created (user inputs this), i want the turtles to be spread on this line evenly. How to do it? It has do to with the line that i wrote and maybe the k value or the 10.

The line is illustrated in the picture (see link below), its the red line, that the number of turtles are created at.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

此岸叶落 2024-10-12 16:06:19

将窗口的 height - 100 除以海龟的数量,即可得到 distanceBetweenTurles

int nrTurtles = Keyboard.nextInt("Set amount of turtles: ");

int height = 300;
w = new GraphicsWindow(500, height);

drawLinez();

double distanceBetweenTurles = (height - 100.0) / nrTurtles;

for (int k = 1; k <= nrTurtles; k++) {
    Turtle t = new Turtle(w, 50, 50 + (int) (k * distanceBetweenTurtles));
    t.right(90);
    t.setSpeed(100);
    t.penDown();
    turtles.add(t);
}

Devide the height - 100 of the window by the number of turtles and you will have your distanceBetweenTurles:

int nrTurtles = Keyboard.nextInt("Set amount of turtles: ");

int height = 300;
w = new GraphicsWindow(500, height);

drawLinez();

double distanceBetweenTurles = (height - 100.0) / nrTurtles;

for (int k = 1; k <= nrTurtles; k++) {
    Turtle t = new Turtle(w, 50, 50 + (int) (k * distanceBetweenTurtles));
    t.right(90);
    t.setSpeed(100);
    t.penDown();
    turtles.add(t);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文