Reputation: 471
I'm writing a 2d Top-down RPG using the LWJGL alongside with Java 1.6. By now, I have the rendering and input methods working fine and just started to program the game's logic.
So I have a class called World, which holds an ArrayList of Entities. I want to implement simple collision in the game (using intersecting squares), which should be no problem. The only problem I now have is how to access single cells of my List without having to iterate all over it. I have only been able to come up with collision methods which are executed inside each Entity and iterate over all of the entities in my World. That is not fast at all, but I really don't know what to do in order to make it faster.
My game is tile based, but the movement is not tile-to-tile, one can walk smaller portions, which avoids me to simply use a two-dimensional array...
Is there a standard way to handle entities and their collisions? (or maybe a way to handle collision between entities which are located inside an ArrayList?)
Upvotes: 3
Views: 1537
Reputation: 8206
The standard way to handle colliding entities is by space partitioning. Your world is a 2 dimensional plane made of discrete points. Each piece can be located on one of the points. The amount of the points determines the resolution of the plane- the more points, the better visual effect, the more calculations you have to perform. This is the trade off.
You can maintain a map between the location of an entity and the entity itself, where the location is represented by an object that overrides equals and getHashCode. The location object contains two members- the X and Y coordinates.
Note- you have to override in a proper and efficient manner.
So you you can access each entity very quickly if you know its coordinate, reshuffling is simply removing an entity and adding it with new coordinates (this can be optimized for locality) and collision detection is trivial- just check whether the same location is occupied by a certain entity.
I would also refer you to this question on SO.
Upvotes: 1