简体   繁体   中英

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.

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.

My first thought is to maintain a hash map of no-user boxes where the key= position of a box and value = box object . Every time the players box moves you want to fire an event that triggers a check for collisions. When the event is triggered you just say

public void checkForCollision(Position currentPosition){
// do not go further if no collision
if (!boxes.containsKey(currentPosition)){ return }

//this part will only execute if there is a collission
boxes.get(currentPosition).makeItDissapear();
}

Prerequisites: - an object describing the boxes properties - research google's EventBus to easily manage envents

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM