gpt4 book ai didi

java - 如何让多个物体随机移动?

转载 作者:行者123 更新时间:2023-12-05 04:38:23 28 4
gpt4 key购买 nike

我正在尝试在 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;
}
}

最佳答案

椭圆已经有了位置属性,所以只需添加一个移动它们的方法就可以了。如果你想让它们真实地与墙壁碰撞,你需要给每个椭圆一个初始的随机速度。然后,您根据当前速度和间隔长度以设定的时间间隔更新位置。例如:

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
}

}

关于java - 如何让多个物体随机移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70616464/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com