Search code examples
javacollision-detectiongame-physics

How do I make objects disappear after another one touches it?


I am working on a small game in Java where you are playing as one small box and the goal is to touch other boxes. You move around using buttons and when you touch another box I want the box that isn't the one the player is to disappear.

I am not sure how to detect when the boxes are touching each other.

I am thinking something like:

if (mainBox is touching otherBox){
    otherBox.disappears();
}

Any help would be appreciated.


Solution

  • Typical collision logic is done by comparing points.

    Since the typical draw point of your square is the top left, the basic logic is this:

    p = playerBox
    t = targetBox
    
    if((t.x>=p.x && t.x<=p.x+p.w) || (t.x+t.w>=p.x && t.x+t.w<=p.x+p.w)){
         if((t.y>=p.y && t.y<=p.y+p.h) || (t.y+t.h>=p.y && t.y+t.h<=p.y+p.h){
              System.out.println("Player p collided with target t!");
         }
    }
    

    May be a bit hard to read but the basic idea is to check if any point of the target is inside the player.