所以我想要 10 个球上下弹跳。到目前为止,我已经成功让 1 个球弹起,并具有重力之类的东西。 但现在我想添加更多的球,但我就是做不到。到目前为止,我尝试添加一个数组,然后使用循环,但我尝试的任何方法都对我不起作用。 如果有人能指出解决方案,我将不胜感激。
Ball b;
void setup() {
size(940, 660);
b = new Ball();
}
void draw() {
background(50);
fill(255);
b.display();
b.move();
}
和类(class):
class Ball
{
float circleX;
float circleY;
float speed;
float gravity=0.2;
Ball() {
speed = 0;
circleY = 0;
circleX = 200;
}
void move() {
speed = speed + gravity; //gravity draufrechnen
circleY = circleY + speed; //mit der geschwindigkeit bewegegn
if (circleY >= height){
speed = -speed; //andere richtung
circleY = height;
speed = speed*0.9;
}
}
void display() {
stroke(0);
fill(127);
ellipse(circleX, circleY, 50 , 50);
}
}
最佳答案
在 balls 中创建一个构造函数,您可以在其中传递球的初始 x 和 y 坐标:
class Ball
{
.....
Ball(int x, int y) {
speed = 0;
circleX = x;
circleY = y;
}
.....
}
创建一个球数组并在setup
函数中初始化它:
int no_of_balls = 10;
Ball[] balls = new Ball[no_of_balls];
void setup() {
for (int i=0; i<no_of_balls; ++i) {
balls[i] = new Ball(80 + i*80, i*5);
}
size(940, 660);
}
可以使用 Math.random()
使用不同的起始高度来初始化球:
for (int i=0; i<no_of_balls; ++i) {
balls[i] = new Ball( 80 + i*80, (int)(Math.random()*100.0) );
}
显示
和移动
绘制
中的球数组:
void draw() {
background(50);
fill(255);
for (int i=0; i<no_of_balls; ++i) {
balls[i].display();
balls[i].move();
}
}
预览(缩小):
关于java - 弹跳球,努力获得超过 1 个球(正在处理),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53454196/