Tuesday, November 8, 2016

java - Making an efficient collision detection system


I'm very new to game development (just started 3 months ago) and I'm learning through creating a game engine. It's located here. In terms of collision, I know only brute-force detection, in which case, the game slows down if there are a number of objects. So my question is How should I program the collisions?


I want them to happen automatically for every object and call the object's collision(GObject other) method on each collision.


Are there any new algorithms which can make this fast? If so, can anybody shed some light on this topic?




Answer



I have seen your game samples. In this specific case I would use a grid. Divide the game screen into squares. Create a 2D-Array representing the game screen squares and containing reference to the game objects inside each square (2d array of object lists).


enter image description here


Check for collisions between all the objects that are inside the same squares (that can collide with one another). An average sized object can be in up to four squares at most.


Update the 2d-array every time you move an object. The object 'remembers' in which squares it is, so you only need to update 8 squares at most even if the object teleports away.


It is one of the best solutions as far as average running time goes because you only need to update once per-object and in most cases, you only need to check for collision once or less per-object. For instance in the space shooter, you would only be checking spaceships that are in the same square with a bullet.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...