弹跳球,挣扎超过1(处理) [英] Bouncing Balls, struggling with getting more than 1 (processing)

查看:53
本文介绍了弹跳球,挣扎超过1(处理)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

以及班级:

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


推荐答案

创建球中的构造函数,您可以在其中传递球的初始x和y坐标:

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

    .....  
}

创建一个球数组并在 setup 函数中对其进行初始化:

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

使用 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();
    }
}

预览(按比例缩小):

这篇关于弹跳球,挣扎超过1(处理)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆