0
我的代碼出現問題。我想在屏幕的兩側打一個球,球由用戶控制,另一個由電腦控制。兩個球互相射擊,如果子彈與另一個相交,我需要做些事情。我在這裏做了一些事情,我有兩個班級,一個是玩家子彈,另一個是敵人子彈,子彈是通過陣列列表創建的。所有的作品都會直到現在,但如果我嘗試使它們相互碰撞,它根本不起作用。我嘗試了很多東西,但都沒有成功,如果有人能幫助我,我會很感激。如何處理兩個arraylist對象之間的碰撞?
也就是說玩家彈丸類:
import java.awt.Rectangle;
public class Projectiles {
private int x, y, speedX;
private boolean visible;
private int width = 10;
private int height = 10;
private Rectangle r;
public Projectiles(){
}
public Projectiles(int startX, int startY) {
x = startX;
y = startY;
speedX = 1;
visible = true;
r = new Rectangle(0, 0, 0, 0);
}
public void update(){
x += speedX;
r.setBounds(x, y, width, height);
if (x > 800){
visible = false;
r = null;
}
if (x < 800){
checkCollision();
}
}
private void checkCollision() {
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getSpeedX() {
return speedX;
}
public boolean isVisible() {
return visible;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void setSpeedX(int speedX) {
this.speedX = speedX;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public void setWidth(int width) {
this.width = width;
}
public void setHeight(int height) {
this.height = height;
}
public Rectangle getR() {
return r;
}
public void setR(Rectangle r) {
this.r = r;
}
}
而這一次是Enemy_Projectile類:
import java.awt.Rectangle;
public class Enemy_Projectiles {
private int x, y, speedX;
private boolean visible;
private int width = 30;
private int height = 20;
public static Rectangle r;
Projectiles p1;
public Enemy_Projectiles(int startX, int startY) {
x = startX;
y = startY;
speedX = 1;
visible = true;
r = new Rectangle(0, 0, 0, 0);
}
public void update() {
x -= speedX;
r.setBounds(x, y, width, height);
if (x < 0) {
visible = false;
r = null;
}
if (x > 0){
checkCollision();
}
}
private void checkCollision() {
if(r.intersects(p1.getR())){
visible = false;
System.out.println("Coliziune!!");
}
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getSpeedX() {
return speedX;
}
public boolean isVisible() {
return visible;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void setSpeedX(int speedX) {
this.speedX = speedX;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public void setWidth(int width) {
this.width = width;
}
public void setHeight(int height) {
this.height = height;
}
}
「我已經嘗試了很多東西,但沒有一個能夠奏效。」你在碰撞方面嘗試了什麼,而什麼對它沒有影響?我們不需要對所有代碼進行排序,以幫助解決這個問題。考慮製作[MCVE](http://stackoverflow.com/help/mcve)。 – csmckelvey
你可以發佈你爲'intersects(...)'方法試過的東西嗎? – Christian
是的,我看到你叫它,但我沒有看到它在任何地方定義。 – csmckelvey