[英]Game collision detection with rectangles
我已經開始了我的第一場比賽,但無法弄清楚碰撞檢測應該如何工作。 目標是玩家不能進入牆壁。
我有以下類 Player()、Wall()、Levels() 和 Game()
Player 類正在加載播放器並處理播放器的移動和碰撞。
Wall 正在創建牆壁,我在這個類中有一個 Arraylist,它為每個創建的牆壁創建一個矩形。
Levels 類正在加載創建和加載所有級別。
游戲類正在處理整個游戲循環等等。
我曾嘗試將 x 和 y 位置與玩家和牆壁進行比較,現在我正在嘗試使用尚未成功的 .intersect 類。
部分球員等級:
public void collision() {
Rectangle r3 = getOffsetBounds();
for (int i = 0; i < Wall.wallList.size(); i++) {
Rectangle w1 = Wall.wallList.get(i);
if (r3.intersects(w1)) {
}}}
public int moveUp(int velY) {
collision();
y -= velY;
return y;
}
public int moveDown(int velY) {
collision();
y += velY;
return y;
}
public int moveLeft(int velX) {
collision();
x -= velX;
return x;
}
public int moveRight(int velX) {
collision();
x += velX;
return x;
}
public Rectangle getOffsetBounds() {
return new Rectangle(x + velX, y + velY, width, height);
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getVelX() {
return velX;
}
public void setVelX(int velX) {
this.velX = velX;
}
public int getVelY() {
return velY;
}
public void setVelY(int velY) {
this.velY = velY;
}}
牆類的一部分:
static ArrayList<Rectangle> wallList = new ArrayList<Rectangle>();
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public void setVisisble(Boolean visible) {
this.visible = visible;
}
public Rectangle getBounds() {
return new Rectangle(x,y,width,height);
}
public Rectangle setBounds(int x,int y,int width,int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
return new Rectangle(x,y,width,height);
}}
設置牆列表的 Levels 類的一部分
if(level1[i][j]==1) {
w = new Wall(j*25, i*25, width, height);
w.paint(g);
Wall.wallList.add(w.setBounds(j*25+10, i*25+10, width, height));
}
鍵綁定所在的游戲類的一部分
public void KeyBindings() {
keyManager.addKeyBinding(lvl, KeyEvent.VK_UP, "moveUp", (evt) -> {
lvl.player.moveUp(5);
});
keyManager.addKeyBinding(lvl, KeyEvent.VK_DOWN, "moveDown", (evt) -> {
lvl.player.moveDown(5);
});
keyManager.addKeyBinding(lvl, KeyEvent.VK_LEFT, "moveLeft", (evt) -> {
lvl.player.moveLeft(5);
});
keyManager.addKeyBinding(lvl, KeyEvent.VK_RIGHT, "moveRight", (evt) -> {
lvl.player.moveRight(5);
});
}
這就是我總是處理任何碰撞的方式
if (((x1<x2 && x1+w1>x2) || (x2<x1 && x2+w2>x1)) &&
((y1<y2 && y1+h1>y2) || (y2<y1 && y2+h2>y1)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.