[英]Collision Detection in Java 2D Not Working Properly
所以基本上在過去的一個半年齡里,我一直試圖讓這個盒子人(玩家)當他與另一個盒子相撞時,他會停止向他與盒子相撞的方向移動。這有點成功,但在看似隨機的時刻,如果我向上移動並擊中玩家左側的盒子,它可能會撞到與之相撞的盒子中並飛下來。 每個方向都是一樣的。
public int checkCollision(ID id){
for(int i = 0; i < handler.obj.size(); i++){ //Cycles through all the objects
GameObject go = handler.obj.get(i); //Stores a temp GameObject
if(go.getID() == id){ //Checks if the id matches and if so do the collision stuff.
if(getBoundsT().intersects(go.getBounds())){
System.out.println("collided top");
y = go.getY() + go.getHeight();
velY = 0;
return 0; //Top side
}
if(getBoundsB().intersects(go.getBounds())){
System.out.println("collided bottom");
y = go.getY() - height;
velY = 0;
return 1; //Bottom side
}
if(getBoundsL().intersects(go.getBounds())){
x = go.getX() + width;
velX = 0;
System.out.println("collided left");
return 2; //Left Side
}
if(getBoundsR().intersects(go.getBounds())){
System.out.println("collided right");
x = go.getX() - width;
velX = 0;
return 3; //Right Side
}
if(getBounds().intersects(go.getBounds())){
System.out.println("collided on all sides");
return 4; //All the sides
}
}
}
return 5; //No Collision
}
checkCollision 方法每秒調用 60 次。 getBounds(l/r/u/d) 函數只返回與字母對應的左、右、上(上)或下(下)邊的矩形。 Id 就是玩家正在碰撞的東西。 在這種情況下,它是牆,所以無論它在哪里說 id 都是牆。 (我已經確保矩形不會超出它們應該出現的區域。)
我已經嘗試了我能想到的一切,所以任何幫助將不勝感激! (這是我的第一個問題,如果寫的很糟糕,請見諒)
編輯:相交代碼 (getBounds) 這是所有對象繼承的 GameObject 類。
public Rectangle getBoundsB() {
return new Rectangle((int)(x + (width/2) - (width/4)), (int)(y + height/2), (int)(width / 2), (int)(height / 2));
}
public Rectangle getBoundsT() {
return new Rectangle((int)(x + (width/2) - (int)(width/4)), (int) y, (int)width / 2, (int)(height / 2));
}
public Rectangle getBoundsR() {
return new Rectangle((int)(x + width - 5), (int)(y + 5), 5, (int)(height - 10));
}
public Rectangle getBoundsL() {
return new Rectangle((int)x, (int)(y + 5), 5, (int)(height - 10));
}
public Rectangle getBounds() {
return new Rectangle((int)x, (int)y, (int)width, (int)height);
}
在 tick 方法中(每 60 秒調用一次):
checkCollision(ID.Wall);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.