【发布时间】:2020-10-19 10:03:46
【问题描述】:
我是一名新手,正在为我的作业编写代码并进行碰撞检测项目。我认为我的算法是正确的,但我的问题是如何从我创建的 ArrayList 访问对象并在检测到碰撞后删除该对象。请查看我的代码并帮助我改进它以从中添加 remove() 。我添加了一个布尔变量来检查是真还是假,然后执行删除功能。
我的最终目标是在幽灵与绿球碰撞时将其移除
ArrayList<Greenball> array1 = new ArrayList<Greenball>();
ArrayList<Ghost> array2 = new ArrayList<Ghost>();
void setup(){
size(1000,500);
}
void draw(){
background(255);
for(int i = 0; i < array1.size() ; i++){
array1.get(i).move();
array1.get(i).display();
}
for (int i = 0; i < array2.size() ; i++){
array2.get(i).move();
array2.get(i).display();
}
}
void mousePressed(){
if (array1.size() != 5) array1.add(new Greenball(int(mouseX),int(mouseY), 40, 40)); //max at 5
}
void keyPressed(){
if (array2.size() != 5)array2.add(new Ghost(int(random(40,960)), int(random(40,460)), 40, 40)); //max at 5
class Ghost{
PImage ghost;
int x,y,w,h,xSpeed,ySpeed;
int pixelSize = 40;
Ghost(int x_, int y_, int w_, int h_){
x = x_;
y = y_;
w = w_;
h = h_;
xSpeed = int(random(-10,10));
ySpeed = int(random(1,10));
}
void move(){
x = x + xSpeed;
y = y + ySpeed;
if(x > width-pixelSize || x < 0){
xSpeed = xSpeed * -1;
}
if(y > height-pixelSize || y < 0){
ySpeed = ySpeed * -1;
}
}
void display(){
ghost = loadImage("greenghost.png");
image(ghost,x,y,w,h);
}
class Greenball{
PImage g;
int x,y,w,h,xSpeed,ySpeed;
int pixelSize = 40;
boolean alive=true;
Greenball(int x_, int y_, int w_, int h_){
x = x_;
y = y_;
w = w_;
h = h_;
xSpeed = int(random(-10,10));
ySpeed = int(random(1,10));
}
void move(){
x = x + xSpeed;
y = y + ySpeed;
if(x > width-pixelSize || x < 0){
xSpeed = xSpeed * -1;
}
if(y > height-pixelSize || y < 0){
ySpeed = ySpeed * -1;
}
}
void display(){
g = loadImage("green.png");
image(g,x,y,w,h);
}
void checkForCollision(Ghost ghost){
float d = dist(x,y,ghost.x,ghost.y);
float r1 = (x+y)/2;
float r2 = (ghost.x + ghost.y)/2;
if (d < r1 + r2) alive = false;
else alive = true;
}
}
【问题讨论】:
-
我被困在幽灵物体与绿球碰撞后如何移除它。我不知道该怎么做。
-
"我将如何从我的 ArrayList 访问对象" 访问是为了什么?对于程序的其他部分,您必须经常访问它。有什么不同吗?为什么要“检测到碰撞后移除对象”。只是将其标记为“被驱除”不是一种选择吗?您可以跳过显示和程序的其他逻辑中的被驱除的鬼魂。
标签: java processing collision-detection