Back to Game Development

Module 4: Game Physics & Math

Master vectors, collision detection, physics simulation, raycasting, and pathfinding algorithms

⚡ What is Game Physics?

Imagine throwing a ball - it follows an arc, bounces off walls, and eventually stops. Game physics simulates real-world behavior to make games feel natural and responsive. It's the math and algorithms that make objects move, collide, and interact realistically!

Simple Definition

Game Physics is the simulation of physical systems - gravity, momentum, friction, collisions - using math. It makes games feel "right" even if it's not 100% realistic. Fun > Realism!

Physics makes possible:

• Realistic movement and jumping

• Objects bouncing and rolling

• Ragdoll character deaths

• Destructible environments

• Vehicle handling

Why Learn Game Physics?

Realistic Gameplay

Make games feel natural and satisfying

Problem Solving

Understand how to implement any game mechanic

Performance

Optimize physics for smooth gameplay

AI and Pathfinding

Make smart enemies that navigate your world

📚 Learn More:

📐 Vectors and Transformations

Vectors are the foundation of game math! A vector is just a direction and magnitude (length). Think of it as an arrow pointing somewhere. Vectors represent position, velocity, force, and more.

Understanding Vectors

A Vector3 in 3D space has three components: X (left/right), Y (up/down), Z (forward/back). Vector2 is the same but only X and Y (for 2D games).

// Creating vectors in Unity

Vector3 position = new Vector3(5, 2, 10); // X=5, Y=2, Z=10

Vector3 velocity = new Vector3(1, 0, 0); // Moving right

// Common vector shortcuts

Vector3.zero // (0, 0, 0)

Vector3.one // (1, 1, 1)

Vector3.up // (0, 1, 0)

Vector3.forward // (0, 0, 1)

Vector3.right // (1, 0, 0)

Vector Operations

// Addition: Combine vectors

Vector3 a = new Vector3(1, 2, 3);

Vector3 b = new Vector3(4, 5, 6);

Vector3 sum = a + b; // (5, 7, 9)

// Subtraction: Direction from A to B

Vector3 direction = targetPos - currentPos;

// Multiplication: Scale vector

Vector3 doubled = velocity * 2; // Twice as fast

// Magnitude: Length of vector

float distance = direction.magnitude;

// Normalize: Make length = 1 (direction only)

Vector3 normalized = direction.normalized;

// Dot Product: How aligned are two vectors?

float dot = Vector3.Dot(forward, toTarget);

// dot > 0: same direction, < 0: opposite, = 0: perpendicular

// Cross Product: Perpendicular vector

Vector3 perpendicular = Vector3.Cross(a, b);

💡 Real-World Uses:

  • Movement: position += velocity * Time.deltaTime
  • Distance: (target - current).magnitude
  • Direction: (target - current).normalized
  • Facing check: Dot product > 0 means facing target

💥 Collision Detection Algorithms

Collision detection determines when objects touch or overlap. It's essential for gameplay - bullets hitting enemies, player collecting coins, character standing on ground. Let's learn the algorithms!

Basic Collision Types

Circle vs Circle (2D)

Two circles collide if the distance between their centers is less than the sum of their radii.

bool CircleCollision(Vector2 pos1, float r1, Vector2 pos2, float r2)

{

float distance = Vector2.Distance(pos1, pos2);

return distance < (r1 + r2);

}

AABB (Axis-Aligned Bounding Box)

Rectangles aligned with axes. Fast and simple! Check if boxes overlap on both X and Y axes.

bool AABBCollision(Rect a, Rect b)

{

return a.xMin < b.xMax &&

a.xMax > b.xMin &&

a.yMin < b.yMax &&

a.yMax > b.yMin;

}

Sphere vs Sphere (3D)

Same as circle collision but in 3D space. Very fast and commonly used!

bool SphereCollision(Vector3 pos1, float r1, Vector3 pos2, float r2)

{

float distSqr = (pos2 - pos1).sqrMagnitude;

float radiusSum = r1 + r2;

return distSqr < radiusSum * radiusSum; // Avoid sqrt!

}

🎯 Performance Tips:

  • • Use sqrMagnitude instead of magnitude (avoids expensive sqrt)
  • • Use simple shapes (sphere, box) for collision, detailed mesh for visuals
  • • Spatial partitioning: Only check nearby objects (quadtree, octree)
  • • Layers: Only check collisions between relevant object types

🎱 Rigidbody Physics Simulation

Rigidbody physics simulates realistic object behavior - gravity, momentum, friction, bouncing. Unity's physics engine handles the complex math, you just set properties and apply forces!

Physics Forces

// Different ways to apply forces

Rigidbody rb = GetComponent<Rigidbody>();

// 1. AddForce - Gradual acceleration

rb.AddForce(Vector3.forward * 10f); // Push forward

// 2. AddForce with ForceMode.Impulse - Instant velocity change

rb.AddForce(Vector3.up * 5f, ForceMode.Impulse); // Jump!

// 3. Velocity - Direct control (use sparingly)

rb.velocity = new Vector3(5, rb.velocity.y, 0); // Set horizontal speed

// 4. AddTorque - Rotation force

rb.AddTorque(Vector3.up * 10f); // Spin around Y axis

// 5. AddExplosionForce - Radial blast

rb.AddExplosionForce(1000f, explosionPos, 10f);

Physics Materials

Physics Materials control friction and bounciness. Create different feels - ice (low friction), rubber (high bounce), concrete (no bounce).

Dynamic Friction: Friction while moving (0 = ice, 1 = sticky)

Static Friction: Friction when stationary

Bounciness: How much energy retained in bounce (0 = no bounce, 1 = perfect bounce)

Friction Combine: How to combine with other materials (Average, Multiply, Min, Max)

Bounce Combine: Same for bounciness

💡 Physics Tips:

  • • Use FixedUpdate() for physics code, not Update()
  • • Keep Rigidbody mass realistic (car = 1000, person = 70)
  • • Freeze rotation axes to prevent unwanted spinning
  • • Use continuous collision detection for fast-moving objects

🎯 Raycasting

Raycasting shoots an invisible ray to detect what it hits. Perfect for shooting games, line-of-sight checks, ground detection, and interaction systems. It's like a laser pointer that tells you what it's pointing at!

Basic Raycasting

// Simple raycast - did we hit something?

if (Physics.Raycast(transform.position, transform.forward, 100f))

{

Debug.Log("Hit something!");

}

// Get hit information

RaycastHit hit;

if (Physics.Raycast(transform.position, transform.forward, out hit, 100f))

{

Debug.Log("Hit: " + hit.collider.name);

Debug.Log("Distance: " + hit.distance);

Debug.Log("Point: " + hit.point);

Debug.Log("Normal: " + hit.normal);

}

// Raycast with layer mask (only hit specific layers)

int layerMask = LayerMask.GetMask("Enemy", "Environment");

if (Physics.Raycast(origin, direction, out hit, 100f, layerMask))

{

// Only hits objects on Enemy or Environment layers

}

Practical Raycast Examples

Ground Check

bool IsGrounded()

{

return Physics.Raycast(

transform.position,

Vector3.down,

1.1f // Slightly more than player height

);

}

Shooting System

void Shoot()

{

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

RaycastHit hit;

if (Physics.Raycast(ray, out hit, 1000f))

{

if (hit.collider.CompareTag("Enemy"))

{

hit.collider.GetComponent<Enemy>().TakeDamage(10);

}

}

}

Interaction System

void CheckInteraction()

{

RaycastHit hit;

if (Physics.Raycast(Camera.main.transform.position,

Camera.main.transform.forward,

out hit, 3f))

{

IInteractable interactable = hit.collider.GetComponent<IInteractable>();

if (interactable != null && Input.GetKeyDown(KeyCode.E))

{

interactable.Interact();

}

}

}

🗺️ Pathfinding with A* Algorithm

Pathfinding helps AI navigate from point A to B, avoiding obstacles. The A* (A-star) algorithm is the industry standard - it finds the shortest path efficiently. Think of it like GPS for game characters!

How A* Works

1. Create a Grid

Divide your world into a grid of nodes. Each node is either walkable or blocked.

2. Calculate Costs

For each node, calculate: G cost (distance from start) + H cost (estimated distance to goal) = F cost (total)

3. Find Path

Start at beginning, always move to neighbor with lowest F cost, repeat until reaching goal.

4. Reconstruct Path

Work backwards from goal to start, following parent nodes.

Unity NavMesh (Easy Pathfinding)

Setting Up NavMesh:

1. Select ground objects → Window → AI → Navigation

2. In Navigation window, mark objects as "Navigation Static"

3. Click "Bake" to generate NavMesh

4. Add NavMeshAgent component to AI character

5. Set destination in code!

// Simple AI that follows player

using UnityEngine.AI;

public class EnemyAI : MonoBehaviour

{

public Transform target;

private NavMeshAgent agent;

void Start()

{

agent = GetComponent<NavMeshAgent>();

}

void Update()

{

// Set destination to player position

agent.SetDestination(target.position);

// Check if reached destination

if (agent.remainingDistance < 1f)

{

Debug.Log("Reached player!");

}

}

}

🎯 Pathfinding Tips:

  • • Use NavMesh for most games - it's fast and easy!
  • • Bake NavMesh at build time, not runtime (slow)
  • • Set NavMeshAgent speed, acceleration, and stopping distance
  • • Use NavMesh obstacles for dynamic objects
  • • For 2D games, implement simple A* or use assets

🎯 Complete Example: Physics-Based Puzzle Game

Let's build a physics puzzle game where you shoot balls to knock down targets! This demonstrates rigidbody physics, raycasting, collision detection, and forces.

// BallShooter.cs - Shoot physics balls

using UnityEngine;

public class BallShooter : MonoBehaviour

{

public GameObject ballPrefab;

public float shootForce = 20f;

public Transform shootPoint;

void Update()

{

if (Input.GetMouseButtonDown(0))

{

ShootBall();

}

}

void ShootBall()

{

// Create ball

GameObject ball = Instantiate(ballPrefab, shootPoint.position, shootPoint.rotation);

// Get rigidbody and apply force

Rigidbody rb = ball.GetComponent<Rigidbody>();

rb.AddForce(shootPoint.forward * shootForce, ForceMode.Impulse);

// Destroy after 5 seconds

Destroy(ball, 5f);

}

}

🎓 What You've Learned:

  • • Vector math for movement and direction
  • • Collision detection algorithms
  • • Rigidbody physics and forces
  • • Raycasting for interactions
  • • Pathfinding with NavMesh
  • • Complete physics-based gameplay!

📚 Learning Resources

Physics & Math

Advanced Topics

🎯 What's Next?

You now understand game physics and math! In the next module, we'll dive into Game AI Programming - learning Finite State Machines, Behavior Trees, and creating intelligent enemies that challenge players!