2
votes

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

1 Answers

3
votes

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