DEV Community

Cover image for OpenGL Collisions
Suvin Nimnaka
Suvin Nimnaka

Posted on

OpenGL Collisions

In simple terms, when an object makes contact with another object, a collision occurs. OpenGL uses various collision detection techniques to detect collisions that happen in your scene maintaining frame rate. The most primitive one is to approximate each object or a part of the object with a simple shapes such as Circles, Rectangles and Points.

Approximating techniques

This is an example of approximating objects inside of a circle. To your left, you can see two complete polygons approximated into circles and to your right, you can see a parts of a polygon approximated into a set of small circles.

Images: Nick Bobic @ GAMASUTRA
Complete Object
Part of the Object

Once the two circle touches or overlaps each other, a collision occurs.However there is one problem with approximation technique. After approximating into a simple shape, a collision occurs when the bounding shapes touches each other or overlaps each other. So as you can see in the above images, even though the actual polygons are not colliding, the bounding circles overlaps and collides.

Collision Types

  1. Collision with the wall (wall – object)
  2. Object - object collision
    • Circle – circle
    • Rectangle – rectangle
    • Circle – rectangle
  3. Object - point collision
    • Circle – point
    • Rectangle – point

Circle-Circle Collision

To detect a collision between a circle and another circle, the circle-circle collision algorithm is used.

Imagine two circles with with radius of r1 and r2 respectively.

Alt Text

If we get the distance between the two center points of the circle as d, the two circles touch each other when d = r1 + r2. And they overlap when d < r1 + r2.

Alt Text

So the circle-circle collision algorithm can be defined as follow.

A collision of two circles happen when Radius 1 + Radius 2 > = Distance.
Enter fullscreen mode Exit fullscreen mode

AABB - AABB Collisions

AABB stands for "Axis-Aligned Bounding Box". That means a rectangular shape aligned to the base axes of the scene. If we are using a 2D scene, the base axis being X and Y.

Down below is an example of a circular object, surrounded by an AABB.

Alt Text

Image: Learn OpenGL

When detecting collisions, We have to consider the both X and Y axis. Consider the following two AABBs.

Alt Text

We can calculate the X range and Y range of the boxes separately as shown in the image above.

When the ranges collapse on each other on either axis, a collision occurs.

Alt Text

Image: Mozilla MDN

In the image above, you can see the X ranges are overlapping. Therefore a collision will occur. Same happens with the Y axis as well.

So far we discussed basic stuff about collisions, Circle-Circle collisions and AABB collisions. That is it for this blog. If you have any questions or feedback, feel free to comment below! Happy Coding!

Top comments (0)