弹跳球,挣扎超过1(处理)

时间:2018-11-24 00:29:25

标签: java arrays object processing

所以我想让10个球上下弹跳。到目前为止,我设法使1个球反弹,并且具有类似重力的东西。 但是现在我想添加更多的球,但是我只是无法做到这一点。到目前为止,我尝试添加一个数组,然后使用一个循环,但是到目前为止,我还没有尝试过。 如果有人可以向我指出解决方案,将不胜感激。

 Ball b; 

 void setup() {               
   size(940, 660);
   b = new Ball();
 }

 void draw() {
   background(50); 
   fill(255);

   b.display();
   b.move();
 }

和班级

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);
  }
}

1 个答案:

答案 0 :(得分:1)

在球中创建一个构造函数,您可以在其中传递球的初始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) );
}

displaymove draw中的球阵列:

void draw() {
    background(50); 
    fill(255);

    for (int i=0; i<no_of_balls; ++i) {
        balls[i].display();
        balls[i].move();
    }
}

预览(按比例缩小):