On overlap, player gets stuck libgdx Rectangle

岁酱吖の 提交于 2019-12-07 23:16:03

问题


So I'm working on a collision detection code and what i do is when the user rectangle overlaps the rectangle where they cant move, I stop them from moving. So if im moving right and I hit a wall i cant move forward. This works. However if after i hit that wall, I want to move down or up form that point, I get stuck.

This is how i check if the user has colidded

private void checkCollision() {
        for (int x = 0; x < amount; x++) {
            if (collsionRect[x].overlaps(user)) {
                Gdx.app.log(ChromeGame.LOG, "Overlap");
                xD = 0;
                yD = 0;
            }
        }
    }

And this is how I move my user

private void moveUser() {
    // camera.translate(xD, yD);
    player.translate(xD, yD);
    camera.position.set(player.getX(), player.getY(), 0);
    // Gdx.app.log(ChromeGame.LOG, player.getX() + "," + player.getY());
    user = new Rectangle(player.getX(), player.getY(), player.getWidth(),
            player.getHeight());
    checkCollision();
}

In my render method I keep calling the move userMove method till I let go of the keyboard wher eit turns the xD,yD to zero


回答1:


The problem is that you check if rectangles overlap. This means that your character is not colliding unless some part of him is already inside the wall, then he stops moving. The next time you want to move the character he is already colliding (a part of him is inside the wall) and so checkCollision() will set xD, yD to 0 and your character won't move.

The easiest solution to this is to make a "fake" move (interpolation) and check if this new move will make him collide, if he will collide you simply don't accept this new move. In pseudocode

new position = player.x + deltaX, player.y+deltaY
create new rectangle for player from new position
check collision with new rectangle
if not collide player.x += deltaX, player.y+=deltaY


来源:https://stackoverflow.com/questions/18046733/on-overlap-player-gets-stuck-libgdx-rectangle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!