Search code examples
javacollision-detectionpaint

Java Collision Detection Before You Move


I have finally gotten collision detection working by using intersects() between 2 rectangles, and it seems to be working. However the player is just getting stuck in the rectangle and can't move. So I am now trying to check collision before the player moves.

Here is what I have tried:

    if(up == true){
        Rectangle futurerect = new Rectangle(px,py-=5,81,150);
        if(!futurerect.intersects(wallexample)){
            py-=5;
            repaint();
        }
    }
    if(down == true){
        Rectangle futurerect = new Rectangle(px,py+=5,81,150);
        if(!futurerect.intersects(wallexample)){
            py+=5;
            repaint();
        }
    }
    if(left == true){
        Rectangle futurerect = new Rectangle(px-=5,py,81,150);
        if(!futurerect.intersects(wallexample)){
            px-=5;
            repaint();
        }
    }
    if(right == true){
        Rectangle futurerect = new Rectangle(px+=5,py,81,150);
        if(!futurerect.intersects(wallexample)){
            px+=5;
            repaint();
        }
    }

I just create a new rectangle but at where it would be if the player moved, and check if it collides. If it does, don't move.

The problem is, when the player moves into the rectangle, it just slows down. It still moves through the wall but just moves at a slower pace for some reason.

What is causing this issue?


Solution

  • It looks like you aren't checking the correct area because your instantiation of a new Rectangle is incrementing / decrementing the py or px and assigning it that value in the constructor of Rectangle.

    So if you have a player at 0,0 in Cartesian and you want to know if they move up will they hit a wall.

    if (up == true) {
    
        Rectangle futurerect = new Rectangle(px,py-=5,81,150);
    
        if(!futurerect.intersects(wallexample)){
            py-=5;
            repaint();
        }
    }
    

    py is now set to -5 once you instantiate the Rectangle.

    Rectangle futurerect = new Rectangle(px,py-=5,81,150);
    

    because of py-=5 in the second parameter.

    When you perform the intersect inspection it is looking at 0, -5. Once that says "Yes, no wall here" you decrement the py another 5. Now we have a player coord px, py of 0, -10 and you didn't check for a wall in that location.

    Try fixing the logic here so it doesn't assign the new value to px / py:

    Rectangle futureRect = new Rectangle(px, py - 5, 81, 150);