Java & Slick2d - Object Interaction

时间:2017-10-12 09:39:12

标签: java eclipse collision-detection collision slick2d

In a game I am creating with slick2d to learn Java, I have multiple levels each with one Footballer and multiple other units I want the footballer to be able to interact with. I also want the other units to interact with each other (for example multiple Balls colliding with eachother) (note, some of these units are sometimes of the same class as one another e/g multiple Defenders). I am unsure, however how to detect these interactions and update the units appropriately. For example, I have my Footballer:

public class Footballer extends Unit {
    public Footballer(float x, float y){
        super("res/ballerpicture", x, y)
        }
    }

And within this class I have an update function which overrides the update function in the Unit class (allowing me to move the one Footballer according to my input - this is working without issue other than collision detection).

I could then, for example, have loaded on my map 5 balls:

public class Ball extends Unit {
    public Ball(float x, float y){
        super("res/ballpicture", x, y)
        }
    }

For an example, I would like to know how to update any one of the balls upon collision with the Footballer, moving them one tile away from the player each time they collide.

My Unit class includes a move method which moves the unit based on an integer direction (left = 1, right = 2 etc...).

Apologies if I have oversaturated this question or haven't included enough information - I'm relatively new to java.

1 个答案:

答案 0 :(得分:1)

您要找的是collision detection。 所有能够相互交互的对象都可以有一个命中框,这是一种代表对象主体的几何形状的最简单方式。我们可以举例说,你的球有一个圆圈作为命中箱,半径为8像素,你的足球运动员有一个矩形的命中箱,宽度为32像素,高度为32像素。

当两个物体现在都在移动时,你必须检查你的命中空间的边界是否相互交叉,如果是这样的话:做一些事情,如果不继续移动。

在Slick2D中,所有形状都有一个名为intersects(Shape s)的方法,如果两个形状的边界相交,则返回true。所以基本上你只需要为对象实现hitbox(确保在对象移动时更新hitbox),然后检查是否有交叉。有许多不同的方法来实现碰撞检测,互联网正在提供有关该主题的大量资源。我还建议您查看Slick2D的Shape documentation。很难为你编写一个解决方案,因为我不知道你的代码,但我相信你会弄明白,Slick2D为交叉方法的问题提供了一个简单的预先实现的解决方案。

它看起来有点像:

编辑,对于多个球:

//in your update method
for(Ball ball : allBalls){
if(footballer.getHitbox().intersects(ball.getHitbox()){
//get direction of footballer
ball.move(...)
}
}