java - spreading out objects on a line evenly
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.
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);
}
精彩评论