When creating games one of the most basic concepts is collision detection. But, what is collision detection?
The Essence Of Collisions
Collision detection is the art of detecting when an object collides with another object or shape. So essentially, we are checking if one shape overlaps another shape. This is carried out both in 2D and 3D games using Mathematical concepts. As long as you understand a coordinate plane and how to check if a point is within another point, we can detect collisions. Now, by having this basic functionality, we can create a lot of interactions within any game we create.
The Benefits Of Collision Detection
With collision detection, you can create actions or results that happen when you touch other objects. For example, a bullet hitting enemies, characters talking within a specific range, hitting players in a fighting game, and having a ball bounce off a surface like in Pong. All of these are examples of the benefits of collision detection. Now, this is only a start and there are many more examples of collision detection. But, let’s get down to the brass tacks.
How does collision detection actually work when it comes to programming? It’s all about shapes and Math. In this case, let’s keep it simple with squares. In most cases, you’ll never have to see this Math if you’re using a game engine, but understanding the concept is crucial.
Formula Of Collision Detection
For squares, we have to check that any of the corners of the square is within the other square. Thus, we need the x,y, width, and height of the square. Here is an example of this functionality written in code.
As you can see, the code checks that within the other square that at least one corner is within the area of the square in space. If no corners are within the other square, it returns false. This is essentially how collisions work in any game engine, except with a more efficient formula. It’s all a collection of shapes interacting with other shapes.
You can see the result of this code at this link.
Hope this helps you and stay tuned for more content coming soon!