Chapter 9: Physics and Collision Detection
Purpose
In interactive game development, realistic movement and interactions are fundamental to creating engaging experiences. This chapter introduces the basic principles of physics simulation and collision detection using C++. You will learn how to implement velocity, acceleration, and gravity, understand fundamental collision detection algorithms, handle collision responses, and integrate advanced physics engines like Box2D for more complex scenarios. By the end of this chapter, you'll be equipped to create dynamic and responsive game environments where objects interact seamlessly.
Topics Covered
- Basic Physics Simulation
- Collision Detection Algorithms
- Axis-Aligned Bounding Box (AABB)
- Circle Collision
- Collision Response
- Physics Engines Integration
- Project Example: Dynamic Object Interaction
Basic Physics Simulation
Understanding the fundamentals of physics simulation is crucial for creating realistic movements in your games. This section covers velocity, acceleration, and gravity, and how to implement them in C++.
Velocity and Acceleration
- Velocity is the rate of change of an object's position with respect to time.
- Acceleration is the rate of change of velocity with respect to time.
Implementation in C++:
Create a Vector2D class to represent 2D vectors for position, velocity, and acceleration.
class Vector2D {
public:
float x;
float y;
Vector2D(float x_=0, float y_=0) : x(x_), y(y_) {}
Vector2D operator+(const Vector2D& other) const {
return Vector2D(x + other.x, y + other.y);
}
Vector2D& operator+=(const Vector2D& other){
x += other.x;
y += other.y;
return *this;
}
Vector2D operator*(float scalar) const {
return Vector2D(x * scalar, y * scalar);
}
};
Applying Velocity and Acceleration:
class PhysicsObject {
public:
Vector2D position;
Vector2D velocity;
Vector2D acceleration;
void update(float deltaTime){
// Update velocity based on acceleration
velocity += acceleration * deltaTime;
// Update position based on velocity
position += velocity * deltaTime;
}
};
Gravity
Gravity is a constant acceleration that affects objects over time. In most games, gravity acts downwards.
Implementing Gravity:
const Vector2D GRAVITY(0, 9.8f); // Assuming positive y is downwards
class PhysicsObject {
public:
Vector2D position;
Vector2D velocity;
Vector2D acceleration;
void applyGravity(){
acceleration += GRAVITY;
}
void update(float deltaTime){
applyGravity();
velocity += acceleration * deltaTime;
position += velocity * deltaTime;
// Reset acceleration after each update
acceleration = Vector2D(0,0);
}
};
Collision Detection Algorithms
Detecting when objects collide is essential for interactive gameplay. This section explores two fundamental collision detection algorithms: Axis-Aligned Bounding Box (AABB) and Circle Collision.
Axis-Aligned Bounding Box (AABB)
AABB is a straightforward method where each object is enclosed within a rectangle whose edges are aligned with the coordinate axes.
AABB Collision Detection Implementation:
struct AABB {
float x; // Top-left corner x
float y; // Top-left corner y
float width;
float height;
};
bool checkAABBCollision(const AABB& a, const AABB& b){
return (a.x < b.x + b.width &&
a.x + a.width > b.x &&
a.y < b.y + b.height &&
a.y + a.height > b.y);
}
Explanation:
- Two AABBs collide if their projections on both the x-axis and y-axis overlap.
- The function returns
true if a collision is detected; otherwise, it returns false.
Circle Collision
Circle collision detection checks whether the distance between the centers of two circles is less than the sum of their radii.
Circle Collision Detection Implementation:
struct Circle {
float x; // Center x
float y; // Center y
float radius;
};
bool checkCircleCollision(const Circle& a, const Circle& b){
float dx = a.x - b.x;
float dy = a.y - b.y;
float distanceSquared = dx * dx + dy * dy;
float radiusSum = a.radius + b.radius;
return distanceSquared < radiusSum * radiusSum;
}
Explanation:
- Calculate the squared distance between the centers to avoid the computational cost of the square root.
- Compare it with the squared sum of the radii to determine collision.
Collision Response
Once a collision is detected, the game must respond appropriately to maintain realism and prevent objects from overlapping unnaturally. This section covers simple collision responses like bouncing and stopping.
Bouncing Response
In a bouncing response, objects reverse their velocity upon collision, simulating an elastic collision.
Bouncing Implementation:
void respondToCollisionAABB(PhysicsObject& obj, const AABB& platform){
// Simple bounce response by reversing y-velocity
if(obj.velocity.y > 0){
obj.velocity.y = -obj.velocity.y;
// Adjust position to be on top of the platform
obj.position.y = platform.y - obj.height;
}
}
Explanation:
- Check the direction of the velocity to determine the side of collision.
- Reverse the velocity component corresponding to the collision axis.
- Adjust the object's position to prevent it from being stuck inside the platform.
Stopping Response
Sometimes you want objects to stop upon collision, such as a player landing on a platform.
Stopping Implementation:
void respondToCollisionAABBStop(PhysicsObject& obj, const AABB& platform){
if(obj.velocity.y > 0){
obj.velocity.y = 0;
obj.position.y = platform.y - obj.height;
}
}
Explanation:
- Set the velocity to zero to stop movement in the collision axis.
- Adjust the position to place the object correctly.
Physics Engines Integration
For more complex physics simulations, integrating a physics engine like Box2D can save time and provide advanced features such as rigid body dynamics, joint constraints, and more.
Using Box2D with C++
Box2D is a popular 2D physics engine written in C++. Here's a brief overview of how to integrate Box2D into your project.
Setting Up Box2D:
- Installation: Download Box2D from its official repository and follow the installation instructions.
- Include Headers:
#include <Box2D/Box2D.h>
Creating a World:
b2Vec2 gravity(0.0f, 9.8f);
b2World world(gravity);
Defining Bodies:
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(0.0f, 4.0f);
b2Body* body = world.CreateBody(&bodyDef);
b2PolygonShape dynamicBox;
dynamicBox.SetAsBox(1.0f, 1.0f);
b2FixtureDef fixtureDef;
fixtureDef.shape = &dynamicBox;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.3f;
body->CreateFixture(&fixtureDef);
Updating the Physics World:
float32 timeStep = 1.0f / 60.0f;
int32 velocityIterations = 6;
int32 positionIterations = 2;
world.Step(timeStep, velocityIterations, positionIterations);
Explanation:
- b2World: Represents the physics simulation world with defined gravity.
- b2BodyDef: Defines properties of a body such as type and initial position.
- b2PolygonShape: Defines the shape of the body for collision purposes.
- b2FixtureDef: Attaches a shape to a body with physical properties like density and friction.
- world.Step: Advances the physics simulation by a time step, resolving collisions and applying forces.
Benefits of Using Box2D:
- Handles complex collision detection and response.
- Optimized for performance.
- Provides features like joints, motors, and sensors.
- Community support and extensive documentation.
Project Example: Dynamic Object Interaction
To solidify your understanding, let's implement a simple project where a player can jump and collide with platforms and obstacles using basic physics principles.
Project Overview
- Player: Can move left/right and jump.
- Platforms: Static objects the player can land on.
- Obstacles: Objects that the player can collide with.
Step 1: Setting Up the Environment
First, define the Vector2D and PhysicsObject classes as previously discussed.
class Vector2D {
public:
float x;
float y;
Vector2D(float x_=0, float y_=0) : x(x_), y(y_) {}
// ... (operator overloads)
};
class PhysicsObject {
public:
Vector2D position;
Vector2D velocity;
Vector2D acceleration;
float width;
float height;
PhysicsObject(float x=0, float y=0, float w=1, float h=1)
: position(x, y), width(w), height(h), velocity(0,0), acceleration(0,0) {}
void applyGravity(){
const Vector2D GRAVITY(0, 9.8f);
acceleration += GRAVITY;
}
void update(float deltaTime){
applyGravity();
velocity += acceleration * deltaTime;
position += velocity * deltaTime;
acceleration = Vector2D(0,0);
}
AABB getAABB() const {
return AABB{position.x, position.y, width, height};
}
};
Step 2: Creating the Player and Platforms
Initialize the player and a list of platforms.
int main(){
// Create player
PhysicsObject player(50.0f, 50.0f, 2.0f, 2.0f);
// Create platforms
std::vector<AABB> platforms;
platforms.push_back(AABB{0.0f, 100.0f, 100.0f, 10.0f});
platforms.push_back(AABB{20.0f, 70.0f, 50.0f, 10.0f});
// Add more platforms as needed
// Game loop variables
float deltaTime = 1.0f / 60.0f;
bool running = true;
while(running){
// Handle input (pseudo-code)
// if(left key pressed) player.velocity.x -= acceleration
// if(right key pressed) player.velocity.x += acceleration
// if(jump key pressed && onGround) player.velocity.y = -jumpSpeed
// Update player physics
player.update(deltaTime);
// Check collisions with platforms
AABB playerAABB = player.getAABB();
for(auto& platform : platforms){
if(checkAABBCollision(playerAABB, platform)){
// Simple collision response: stop the player and place them on top of the platform
player.velocity.y = 0;
player.position.y = platform.y - player.height;
}
}
// Render the scene (pseudo-code)
// drawPlayer(player.position.x, player.position.y, player.width, player.height)
// drawPlatforms(platforms)
// Update the game state
}
return 0;
}
Explanation:
- Player Movement: The player can move horizontally and jump. Input handling should adjust the player's velocity accordingly.
- Gravity Application: The
applyGravity function continuously accelerates the player downward.
- Collision Detection: After updating the player's position, check for collisions with all platforms. If a collision is detected, adjust the player's position and velocity to simulate landing on the platform.
- Rendering: Visual representation of the player and platforms is handled separately (pseudo-code for simplicity).
Step 3: Enhancing Collision Response
To prevent the player from getting stuck inside platforms or experiencing jittery movement, refine the collision response by determining the collision side and adjusting position and velocity accordingly.
void handleCollisions(PhysicsObject& player, const std::vector<AABB>& platforms){
AABB playerAABB = player.getAABB();
for(auto& platform : platforms){
if(checkAABBCollision(playerAABB, platform)){
// Calculate the depth of the collision on both axes
float depthX = (player.position.x + player.width / 2) - (platform.x + platform.width / 2);
float depthY = (player.position.y + player.height / 2) - (platform.y + platform.height / 2);
float halfWidths = (player.width + platform.width) / 2;
float halfHeights = (player.height + platform.height) / 2;
// Determine the side of collision
float absDepthX = abs(depthX);
float absDepthY = abs(depthY);
if(absDepthX > absDepthY){
// Collision on the y-axis
if(depthY > 0){
// Collision at the bottom
player.position.y = platform.y + platform.height;
}
else{
// Collision at the top
player.position.y = platform.y - player.height;
player.velocity.y = 0;
}
}
else{
// Collision on the x-axis
if(depthX > 0){
// Collision on the right
player.position.x = platform.x + platform.width;
}
else{
// Collision on the left
player.position.x = platform.x - player.width;
}
player.velocity.x = 0;
}
// Update the player's AABB after position adjustment
playerAABB = player.getAABB();
}
}
}
Explanation:
- Collision Depth: Calculate how deep the player has collided into the platform along both axes.
- Collision Side: Compare the absolute depths to determine whether the collision is more significant on the x-axis or y-axis.
- Position Adjustment: Move the player out of the collision along the primary collision axis.
- Velocity Adjustment: Reset the velocity component corresponding to the collision axis to prevent continuous collision detection.
Final Integration into the Game Loop
Incorporate the refined collision handling into the game loop.
while(running){
// Handle input
// ...
// Update player physics
player.update(deltaTime);
// Handle collisions
handleCollisions(player, platforms);
// Render the scene
// ...
// Update the game state
}
Conclusion
This chapter provided a comprehensive introduction to basic physics simulation and collision detection in C++. You learned how to implement fundamental physics concepts like velocity, acceleration, and gravity. Additionally, you explored simple yet effective collision detection algorithms such as AABB and circle collision, and handled collision responses to create realistic interactions between game objects. By integrating these principles, you built a foundational framework for dynamic object interactions within your games.
For more advanced physics interactions, integrating a physics engine like Box2D can significantly enhance your game's realism and complexity. As you continue developing your skills, consider exploring additional physics concepts and engine features to create more intricate and engaging game mechanics.
Exercises
-
Extend Collision Shapes:
- Implement triangle or polygon collision detection alongside AABB and circle collisions.
-
Add More Physics Properties:
- Incorporate properties like mass and apply forces to objects for more dynamic interactions.
-
Implement Friction:
- Simulate friction by adjusting the velocity of objects when they are in contact with surfaces.
-
Use a Physics Engine:
- Integrate Box2D into your project and compare the implementation with the basic physics simulation.
-
Create Moving Platforms:
- Design platforms that move horizontally or vertically and handle collisions with dynamic objects.
Further Reading
- Box2D Documentation: Explore the official Box2D documentation for in-depth understanding and advanced features.
- Game Physics Book by David H. Eberly: A comprehensive resource on various physics simulations applicable to game development.
- Real-Time Collision Detection by Christer Ericson: An essential book focusing on collision detection algorithms and their applications.
By mastering the concepts in this chapter, you lay the groundwork for creating more interactive and physically believable games. Practice implementing these principles and explore advanced topics to further enhance your game development repertoire.