矩形的游戏碰撞检测

Game collision detection with rectangles

我已经开始玩我的第一个游戏,但无法弄清楚碰撞检测应该如何工作。目标是玩家不能进入墙内。

我有以下 classes Player()、Wall()、Levels() 和 Game()

播放器 class 正在加载播放器并为播放器处理移动和碰撞。

Wall 正在创建墙,我在这个 class 中有一个 Arraylist,它正在为每个创建的墙创建一个矩形。

级别 class 正在加载创建和加载所有级别。

游戏 class 正在处理整个游戏循环等等。

我已经尝试将 x 和 y 位置与播放器和墙壁进行比较,现在我正在尝试使用尚未成功的 .intersect class。

部分玩家Class:

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;
}}

墙的一部分 Class:

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);
}}

设置墙列表的部分关卡class

                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));
                }

游戏的一部分 class 其中键绑定是

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)))