Collision Detection in C++ Game Development

Collision Detection in C++ Game Development

In game development, collision detection is a very important aspect. It helps us determine whether interactions occur between objects, such as whether a character collides with an obstacle or a bullet hits an enemy. This article will detail methods for implementing basic collision detection in C++, suitable for beginners to understand and learn.

Overview of Collision Detection

Collision detection is generally divided into two types:

  1. Axis-Aligned Bounding Box (AABB): This is the simplest shape, commonly used in 2D games. Each object is represented by a rectangle.
  2. Circle: Sometimes circles are also used for simple collision checks.

AABB Collision Detection

For two rectangles, we can check if they overlap by their vertex coordinates. Suppose we have two rectangles A and B, which have the following properties:

  • <span>x</span> and <span>y</span> represent the top-left corner coordinates
  • <span>width</span> represents the width
  • <span>height</span> represents the height

Collision Logic

Two rectangles collide if and only if the following four conditions are not met: A’s right side < B’s left side, A’s bottom < B’s top, B’s right side < A’s left side, and B’s bottom < A’s top.

Mathematically, this can be expressed as:

if (A.x + A.width >= B.x &&     A.x <= B.x + B.width &&    A.y + A.height >= B.y &&    A.y <= B.y + B.height) {    // Collision occurs}

Code Demonstration: AABB Collision Detection

#include <iostream>
struct Rectangle {    float x, y;      // Top-left corner coordinates    float width, height; // Width and height};
bool checkCollision(const Rectangle& a, const Rectangle& b) {    return (a.x + a.width >= b.x &&             a.x <= b.x + b.width &&            a.y + a.height >= b.y &&            a.y <= b.y + b.height);}
int main() {    Rectangle rectA = {0, 0, 100, 100};    Rectangle rectB = {50, 50, 100, 100};
    if (checkCollision(rectA, rectB)) {        std::cout << "Collision detected!" << std::endl;    } else {        std::cout << "No collision." << std::endl;    }
    return 0;}

Circle Collision Detection

For further applications, we may need to use circles as our future objects. In this case, we use the center point and radius attributes.

Collision Logic

The distance between the centers of the circles needs to be less than or equal to the sum of their radii. This can be accomplished by calculating the Euclidean distance between the two points:

Let’s define two circles C1 and C2:

  • Center points <span>(x1,y1)</span> and <span>(x2,y2)</span>
  • Radii <span>r1</span>, <span>r2</span>

If:

if (sqrt((x2 - x1)^2 + (y2 - y1)^2) <= r1 + r2)

Then the two circles overlap, indicating a

Leave a Comment