简体   繁体   English

创建新对象Processing.js-随机球程序

[英]Creating new objects Processing.js - Random Ball program

I'm learning to use Processing.JS have have a very basic idea on what I'm doing. 我正在学习使用Processing.JS对我正在做的事情有一个非常基本的想法。 I'm learning to create objects using cases. 我正在学习使用案例创建对象。 The aim of this code is to create random objects (balls) that bounce around the screen and when the mouse is clicked a new ball is created, leaving the original and the new created. 此代码的目的是创建在屏幕周围反弹的随机对象(球),并在单击鼠标时创建一个新球,并保留原来的球和新创建的球。 I want to be able to do this multiple times, with all of the balls randomly bouncing around. 我希望能够多次执行此操作,所有球都随机反弹。 I have the code working for one ball and have the code to a point where I'm creating new objects and they are being added to an array, however every time I click the single ball just gets reset to the middle of the screen. 我的代码适用于一个球,并且代码已达到创建新对象并将它们添加到数组的地步,但是,每次我单击单个球时,都会重置到屏幕中间。 This is the code: 这是代码:

//random ball maker

Ball[] newBall = new Ball[1];

void setup(){
  size(500,500);
  newBall[0] = new Ball();
} 

void draw(){
  //newBall.display();
  // newBall.movement();
  for (int i = 0; i < newBall.length; i++) {  //Loops through all mrect objects
    newBall[i].display();
  }
  for (int i = 0; i < newBall.length; i++) {  //Loops through all mrect objects
    newBall[i].movement();
  }
}

void mousePressed(){
   Ball ballInstance = new Ball();
   newBall = (Ball[]) append(newBall, ballInstance);
}


class Ball{
  float xpos, ypos, xspeed, yspeed;

  Ball(){ 
    xpos = width/2;
    ypos = height/2;
    xspeed = 2;
    yspeed = 2.5;
    println("created new ball");
  } 

  void display(){
    background(100,100,100);
    fill(143,154,189);

    ellipseMode(CENTER);
    ellipse(xpos, ypos, 50,50);

  } 

  void movement(){
  xpos = xpos + xspeed; 
  ypos = ypos + yspeed; 

  if (xpos > width - 25 || xpos < 25){
    xspeed *= -1; }
  if (ypos > height - 25 || ypos < 25){
    yspeed *= -1; }

  }

} 

I feel my issue is with the initiation of the object or with the "void draw" function . 我觉得我的问题是对象的初始化或“无效绘制”功能。 What am I doing wrong?? 我究竟做错了什么??

Calling the background() function clears everything from the screen. 调用background()函数会清除屏幕上的所有内容。

You call background() from inside the display() function in the Ball class. 您可以从Ball类的display()函数内部调用background() That means you draw each ball, but the last ball clears out all of the previous balls. 这意味着您要抽出每个球,但最后一个球会清除所有先前的球。

Move that line to inside the main draw() function. 将该行移到主draw()函数内部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM