# How and where to handle collisions? [Java] [duplicate]

Okay, so in my game I have a Level class, which hold an ArrayList of entities. In addition to this, I store the Player here (naturally enough). In my Entity class, I have a method which checks for collisions. This method looks like this:

public boolean collision(Entity other) {
return cBox.intersects(other.cBox);
}


Now, in my Level class, under the update() method, I check for collisions like this:

for (int i = 0; i < entities.size(); i++) {
if (entities.get(i).collidable() && entities.get(i).collision(player)) {
player.notifyCollision();
}
}


The notifyCollision() method simply ticks a boolean named collision to true in the player class.

This leads me to the question: If I have, say a Chest, an Enemy and some Spikes, where all of them are entities on a map (every entity except for the player is part of the entities ArrayList under the Level class), how would I handle the collisions, and where would I do this?

Say that I want to open a chest if the player is standing in front of it, or hurt the player if it collides with an enemy etc. Would I simply go with the notifyCollision() method, and then have another method named handleCollisions() in the Player class, which would be called if a collision were notified? Or would I have a handleCollision() method under the Chest, Enemy and Spike class, and handle them from here?

Because, the question is really how and where to handle the collisions.

## 1 Answer

Basically objects should define by themselves what happens to them when collision happens and the parent object owning colliding objects should check the collisions and notify the objects colliding each other by calling the collision handler routines.

If your game is simple, you may not even need a specific collision checking interface. For example when player comes near a chest its more intuitive to call an openChest() function than calling handleCollision() function. For your question where the distance between objects should be checked, its a matter of opinions. I would do it the upper way, meaning that the player and the chest would be responsible for their own actions when opening the chest (animations, sounds when opening...) and the level would be responsible between the interaction between the two.

• So I would check for collisions the way I already do in Level, and if a collision between a player and entity is found, then I would call a handleCollision() method, where say, the chest opens and plays sounds etc. Or would I notify a collision, and then handle the collision the next time that entity ticks? Anyways, thank you, I think I am on the right track! ^^ – Caithrine Apr 4 '15 at 21:43