Bouncing Balls, struggling with getting more than 1 (processing)

。_饼干妹妹 提交于 2019-12-11 13:28:19

问题


so I want to have 10 Balls bouncing up and down. So far I have managed to get 1 Ball to bounce, and to have something like gravity. But now I want to add more balls, but I just can`t manage to do so. So far I tried to add an array, and then to use a loop, but nothing I tried worked for me yet. Would appreciate if somebody could point me out to the Solution.

 Ball b; 

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

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

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

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

回答1:


Create a constructor in balls, where you can pass the initial x and y coordinate of a ball:

class Ball 
{
    .....    

    Ball(int x, int y) {
       speed = 0;
       circleX = x;
       circleY = y;
    }

    .....  
}

Create an array of balls and initialize it in the setup function:

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

The balls can be initialized with different start heights by using Math.random():

for (int i=0; i<no_of_balls; ++i) {
    balls[i] = new Ball( 80 + i*80, (int)(Math.random()*100.0) );
}

display and move the array of balls in draw:

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

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

Preview (down scaled):



来源:https://stackoverflow.com/questions/53454196/bouncing-balls-struggling-with-getting-more-than-1-processing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!