java - 弹跳球,努力获得超过 1 个球(正在处理)

标签 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):

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/

相关文章:

java - Java 中有处理命名管道的跨平台方法还是我应该编写自己的方法?

java - WebDriver 等等。无法推断 <V> 的类型参数,直到(Function<? super T,V>)

javascript - 在 React Context 中更新嵌套状态的最佳方法

c - 初始化菜单系统的结构数组时出错

java - 如何在 Selenium 中设置 Chrome 的设置能力?

Java - 如何从 MongoDatabase 类获取 DB 对象,因为 MongoClient.getDB(dbName) 已弃用

c - 将用逗号分隔的文本文件读取到 C 中的二维数组中

c++ - 我无法使用指针数组从 main 访问函数(在类中)

javascript - 循环遍历数组对象

c++ - 嵌套对象中的内存不可用