正如 donfuxx 所建议的那样,为每个球提供自己的坐标。
一种方法是使用数组来存储多个值(坐标)。
为此,您需要熟悉 for 循环和数组。
一开始它们可能看起来很吓人,但一旦你掌握了它们的窍门,它们就很容易了。
只要您能想到需要重复的情况,您都可以使用 for 循环让您的生活更轻松。
For 循环的语法如下:
for keyword (3 elements: a start point,an end point(condition) and an increment,(separated by the ; character)
假设您想一次一步从 a(0) 移动到 b(10):
for(int currentPos = 0 ; currentPos < 10; currentPos++){
println("step: " + currentPos);
}
如果你会走路,你也可以跳过:)
for(int currentPos = 0 ; currentPos < 10; currentPos+=2){
println("step: " + currentPos);
}
如果你愿意,甚至可以倒退:
for(int currentPos = 10 ; currentPos > 0; currentPos--){
println("step: " + currentPos);
}
这在遍历各种数据(场景中球的坐标等)时非常有用
您如何组织数据?你把它放在一个列表或数组中。
数组包含相同类型的元素并具有固定的长度。
声明数组的语法如下:
ObjectType[] nameOfArray;
你可以初始化一个空数组:
int[] fiveNumbers = new int[5];//new keyword then the data type and length in sq.brackets
或者你可以用值初始化数组:
String[] words = {"ini","mini","miny","moe"};
您可以使用方括号和要访问的列表中对象的索引来访问数组中的元素。数组具有长度属性,因此您可以轻松计算对象。
background(255);
String[] words = {"ini","mini","miny","moe"};
for(int i = 0 ; i < words.length; i++){
fill(map(i,0,words.length, 0,255));
text(words[i],10,10*(i+1));
}
现在回到你原来的问题。
这是您使用 for 循环和数组的代码:
int ballSize = 40;
int maxBalls = 100;//maximum number of balls on screen
int screenBalls = 0;//number of balls to update
int[] ballsX = new int[maxBalls];//initialize an empty list/array of x coordinates
int[] ballsY = new int[maxBalls];//...and y coordinates
void setup() {
size(500, 400);
fill(255, 0, 255);
}
void mouseClicked() {
if (screenBalls < maxBalls) {//if still have room in our arrays for new ball coordinates
ballsX[screenBalls] = mouseX;//add the current mouse coordinates(x,y)
ballsY[screenBalls] = mouseY;//to the coordinate arrays at the current ball index
screenBalls++;//increment the ball index
}
}
void draw() {
println(screenBalls);
background(255);
for (int i = 0 ; i < screenBalls; i++) {//start counting from 0 to how many balls are on screen
ballsX[i]++;//increment the x of each ball
if(ballsX[i]-ballSize/2 > width) ballsX[i] = -ballSize/2;//if a ball goes off screen on the right, place it back on screen on the left
ellipse(ballsX[i], ballsY[i], ballSize, ballSize);//display each ball
}
}
有多种方法可以解决这个问题。数组具有固定大小。如果您不想受此限制,则可以使用 ArrayList(一种可变大小的数组)。稍后您可能想研究如何制作一个可以更新和绘制自身的object。玩得开心!