P.Smith
P.Smith

Reputation: 69

OpenGL C++ Circle vs Circle Collision

I am making a 2D game and I have created two circles, one named player and one named enemy. The circles are drawn by calling a drawPlayerCircle and drawEnemyCircle function, both which are called in my display() function. At the moment my project isn't Object Orientated which you can already probably tell. My collision works for both circles as I have calculated penetration vectors and normalised vectors etc... However my question is, expanding this game further by having 10-20 enemies in the game, how can I work out the collision to every single enemy quickly rather than calculating manually the penetration and normalised vectors between my player and every enemy in the game which is obviously very inefficient. I'm guessing splitting my player and enemy entities into their own class but I'm still struggling to visualise how the collision will work.

Any help will be greatly appreciated! :)

Upvotes: 0

Views: 826

Answers (2)

Tamás Zahola
Tamás Zahola

Reputation: 9321

Space partitioning. Specifically, if you're in 2D, you can use a quadtree to speed up collision detection.

Upvotes: 0

Sam
Sam

Reputation: 3480

Collision between two circles is very quick to test. Just check if the distance between the circle centre points is less than the sum of the two radii.

I would just start by comparing the player against every other enemy. Doing 20 comparisons is not going to tax any computer from the last 10 years. I'm a big believer in just writing the code that you need right now and not complicating things, especially when you are just starting out.

However if you end up having millions of circles and you've profiled your code and found that testing all circles is slow, there are quite a few options. The simplest might be to have a grid over the play area.

Each grid cell covers a fixed amount of space over the play area and stores a list of circles. Whenever a circle moves calculate which grid cell it should be in. Remove it from the grid cell that it is currently in, and add it to the grid cell that it should be in. Then you can compare only the circles that overlap the player's grid cell.

Upvotes: 2

Related Questions