0

I am trying to write a collision detection that will detect what side the player is colliding from. I have tried 2 methods and neither has worked. In this example, if the player is colliding from the right side of the tile, then he can go right and slide through the tile to the left and then get stuck once leaving the tile

Here is my collision detection code (I have the player extending an Entity superclass)

public void collide(Entity e) {
    /**
     * Previous code:
    if ((e.x + e.width) == this.x && (e.y < height && e.y > y)) {
        if (e.dx > 0) {
            System.out.println("Collided from left");
            e.dx = 0;
        }
    } else if (e.x == (x + width) && (e.y < height && e.y > y)) {
        if (e.dx < 0) {
            System.out.println("Collided from right");
            e.dx = 0;
        }
    }
    if ((e.y + e.height) == this.y && (e.x < width && e.x > this.x)) {
        if (e.dy > 0) {
            System.out.println("Collided from top");
            e.dy = 0;
        }
    } else if (e.y == (this.y + this.height) && (e.x < width && e.x > this.x)) {
        if (e.dy < 0) {
            System.out.println("Collided from bottom");
            e.dy = 0;
        }
    }
    */

    if(e.collisionBox.intersects(collisionBox) || collisionBox.intersects(e.collisionBox)) {
        if(e.right) {
            if(e.dx > 0 && !colRight) {
                System.out.println("Collided from left");
                e.dx = 0;
                colLeft = true;
                colRight = false;
                e.x -= 1;
            }
        } else if(e.left && !colLeft) {
            if(e.dx < 0) {
                System.out.println("Collided from right");
                e.dx = 0;
                colRight = true;
                colLeft = false;
                e.x += 1;
            }
        }
        if(e.up) {
            if(e.dy < 0) {
                System.out.println("Collided from bottom");
                e.dy = 0;
                e.y += 1;
            }
        } else if(e.down) {
            if(e.dy > 0) {
                System.out.println("Collided from top");
                e.dy = 0;
                e.y -= 1;
            }
        }
    }
}
Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146

0 Answers0