如何使多个物体随机移动?

3

我正在尝试在Processing中制作一种类似于Agar.io的克隆游戏。我已经生成了许多食物点,但我想让它们也移动并从屏幕边缘反弹,增加一些趣味性。然而,我不太确定如何使所有点都随机地移动。

ArrayList<Ellipse> ellipse = new ArrayList <Ellipse>();

//Images
PImage background;
int x = 2;

//Words 
PFont arial;


void setup(){
  size(1920,1080);
  
  //Background change
  if (x == 1){
   background = loadImage("backdrop1.jpg");
}
 if (x == 2){
   background = loadImage("backdrop2.jpg");
}
//Creating the font
arial = createFont ("Arial", 16, true); //the true is for antialiasing

//Load from text file
//tbd...

//Adding the food ellipses

for(int foodSpawn = 0; foodSpawn < 50; foodSpawn++){
  ellipse.add(new Ellipse(random(100,1820),random(100,980), 50, 50));
}
}

void draw(){
  background(background); 
  for(int i = 0; i<ellipse.size(); i++){
  Ellipse e = ellipse.get(i);
  
  fill(#62C3E8);
  ellipse(e.xLoc,e.yLoc, e.eWidth, e.eHeight);
  }
}

class Ellipse {
 float xLoc;
 float yLoc;
 float eWidth;
 float eHeight;
 
 public Ellipse(float xLoc, float yLoc, float eWidth, float eHeight){
   this.xLoc = xLoc;
   this.yLoc = yLoc;
   this.eWidth = eWidth;
   this.eHeight = eHeight;
}
}
1个回答

2

椭圆形已经有位置属性,因此只需添加一个移动方法即可。如果您希望它们与墙壁产生真实的碰撞,您需要为每个椭圆形赋予一个初始随机速度。然后,根据当前速度和时间间隔长度,在设置的时间间隔内更新位置。例如:

public void move() {
    // Note: these are signed, and xvel and vyel are in pixels/second
    float x_move_dist = this.xvel*time_int
    float y_move_dist = this.yvel*time_int

    // Update xloc
    // Check collision with left wall
    if (this.xloc + x_move_dist - this.eWidth/2 < 0) {
        // Assuming conservation of momentum, we can reflect the movement off the wall
        this.xloc = -(this.xloc + x_move_dist + this.eWidth/2)
    }
    // Check collision with right wall
    else if (this.xloc + x_move_dist + this.eWidth/2 > 1920) {
        // Again, reflect off wall
        this.xloc = 1920 - ((this.xloc + x_move_dist) - 1920) - this.eWidth/2
    }
    // Otherwise, just update normally
    else {
        this.xloc = this.xloc + x_move_dist
     }

    // Update yloc
    // Check collision with bottom wall
    if (this.yloc + y_move_dist - this.eHeight/2 < 0) {
        // Again, reflect off wall
        this.yloc = -(this.yloc + y_move_dist) + this.eHeight/2
    }
    // Check collision with top wall
    else if (this.yloc + y_move_dist + this.eHeight/2 > 1080) {
        // Again, reflect off wall
        this.yloc = 1920 - ((this.yloc + y_move_dist) - 1920) - this.eHeight/2
    }
    // Otherwise, just update normally
    else {
        this.yloc = this.yloc + y_move_dist
     }
 
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接