如何在另一个物体接触后使物体消失?

时间:2014-05-27 16:21:56

标签: java collision-detection game-physics

我正在开发一个Java小游戏,你在一个小盒子里玩,目标是触摸其他盒子。你使用按钮移动,当你触摸另一个盒子时,我想要的盒子不是玩家将要消失的盒子。

我不确定如何检测盒子相互接触的时间。

我想的是:

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

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:2)

通过比较点来完成典型的碰撞逻辑。

由于广场的典型绘制点是左上角,基本逻辑是:

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!");
     }
}

可能有点难以阅读,但基本的想法是检查目标的任何一点是否在玩家内部。

答案 1 :(得分:1)

我的第一个想法是维护一个无用户框的哈希图,其中key = 框的位置和value = 框对象。每当玩家框移动时,您想要触发一个触发检查碰撞的事件。 触发事件时,您只需说出

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();
}

先决条件: - 描述框属性的对象 - 研究谷歌的EventBus,轻松管理事件