Game Dev Series: How game physics works with gravity, collisions and hitboxes

Game Dev Series: How Does Game Physics Work? Gravity, Collisions and Hitboxes

The first time I modded a game, I changed one number in a config file and my character jumped over a whole building. It was hilarious, and it was also my first real hint that game physics is not magic. Somewhere in the code there is a gravity value, a jump speed and a loop that runs many times a second. Change one number and the whole feel of the game changes.

Later, when I tried to vibe code a tiny platformer, physics was where things broke the most. My player fell through the floor, got stuck inside walls and jumped higher on my laptop than on my friend’s PC. I am still a modder and vibe coder learning game development honestly, not a physics engineer at a studio.

In this Game Dev Series post I want to unpack the simple ideas under game physics, gravity, velocity, collisions and hitboxes, and show the small bits of code that finally made it click for me.

Game Dev Series: How Does Game Physics Work? Gravity, Collisions and Hitboxes 1
Game Dev Series: How Does Game Physics Work? Gravity, Collisions and Hitboxes 11

What does game physics actually mean?

Real physics is a huge subject. Game physics is a much smaller and friendlier thing. It is a set of rules that runs every tick to answer a few questions. Where is each object now? How fast is it moving? Did it bump into anything? And if it did, what should happen next? Most games do not simulate the real world perfectly. They simulate something that feels right and runs fast.

Every physics update follows roughly the same loop. Forces like gravity or a jump change the velocity. The velocity changes the position. Then the engine checks for overlaps and resolves them, by pushing objects apart, stopping them or bouncing them. Godot’s physics introduction describes the same building blocks with its own names, static bodies, rigid bodies, character bodies and areas.

Game Dev Series: How Does Game Physics Work? Gravity, Collisions and Hitboxes 2
One physics tick. Forces change velocity, velocity changes position, then collisions get detected and resolved.

How does gravity work in a game?

Gravity in a game is usually just a number that gets subtracted from the vertical velocity every step. That is it. You do not need Newton’s full formula, only two lines that run in order. First velocity changes because of gravity. Then position changes because of velocity. A jump is simply setting a big upward velocity once and letting gravity eat it away.

Here is a tiny jump in Python. I use a large step of a tenth of a second so the output fits on screen. Watch the velocity column shrink, hit zero at the peak, then go negative as the player falls.

# Gravity and a jump, one fixed physics step at a time
GRAVITY = 30.0      # units per second squared (pulls down)
JUMP_SPEED = 12.0   # units per second (upward kick)
DT = 1 / 10         # 10 physics steps per second, big so the output stays short
y, vy = 0.0, JUMP_SPEED   # start on the ground and jump straight away
t = 0.0
print(" time   velocity   height")
while True:
    vy -= GRAVITY * DT     # 1. gravity changes velocity
    y += vy * DT           # 2. velocity changes position
    t += DT
    if y <= 0:             # 3. hit the ground, so stop falling
        y, vy = 0.0, 0.0
        print(f"{t:5.1f}   {vy:8.2f}   {y:6.2f}   landed")
        break
    bar = "#" * int(y * 10)
    print(f"{t:5.1f}   {vy:8.2f}   {y:6.2f}   {bar}")
 time   velocity   height
  0.1       9.00     0.90   #########
  0.2       6.00     1.50   ###############
  0.3       3.00     1.80   ##################
  0.4       0.00     1.80   ##################
  0.5      -3.00     1.50   ###############
  0.6      -6.00     0.90   #########
  0.7       0.00     0.00   landed

That bar chart is the whole jump arc printed sideways. Speed goes 9, 6, 3, 0, then -3 and -6, and the height climbs and falls back to the ground. When I saw this I finally understood why tweaking the gravity value in a mod made jumps feel floaty or heavy. Lower gravity keeps the player in the air longer. Higher gravity snaps them back down.

Game Dev Series: How Does Game Physics Work? Gravity, Collisions and Hitboxes 3
Each dot is one physics step. Upward velocity shrinks until the peak, then gravity pulls the player back down.

How do games detect collisions between objects?

Collision detection is the question, are these two things touching right now? The most common answer in 2D games is the axis aligned bounding box, or AABB. Every object gets an invisible rectangle that never rotates. Two boxes collide when they overlap on the x axis and also on the y axis. If there is a gap on either axis, they cannot be touching.

Game Dev Series: How Does Game Physics Work? Gravity, Collisions and Hitboxes 4
Two boxes collide only when they overlap on x and y. A gap on either axis means no collision.

Detecting the hit is only half the job. The other half is collision response, deciding how to fix the overlap. A simple and very popular approach is to push the moving object out along the axis where the overlap is smallest. If the player sank a little into the floor, the smallest fix is to push them up. If they walked into a wall, the smallest fix is to push them sideways.

# Axis aligned bounding box (AABB) overlap test plus a simple push out
from dataclasses import dataclass
@dataclass
class Box:
    name: str
    x: float  # left
    y: float  # top
    w: float
    h: float
def overlaps(a, b):
    return (a.x < b.x + b.w and a.x + a.w > b.x and
            a.y < b.y + b.h and a.y + a.h > b.y)
def push_out(mover, wall):
    """Move `mover` out of `wall` along the axis with the smallest overlap."""
    dx_left = (mover.x + mover.w) - wall.x      # how far to push left
    dx_right = (wall.x + wall.w) - mover.x      # how far to push right
    dy_up = (mover.y + mover.h) - wall.y        # how far to push up
    dy_down = (wall.y + wall.h) - mover.y       # how far to push down
    best = min(dx_left, dx_right, dy_up, dy_down)
    if best == dx_left:  mover.x -= dx_left;  return "pushed left"
    if best == dx_right: mover.x += dx_right; return "pushed right"
    if best == dy_up:    mover.y -= dy_up;    return "pushed up (landed on top)"
    mover.y += dy_down;  return "pushed down (bonked head)"
floor = Box("floor", 0, 10, 20, 2)
wall = Box("wall", 18, 2, 2, 8)
tests = [(Box("player falling", 4, 8.5, 2, 2), floor),
         (Box("player walking into wall", 16.6, 5, 2, 2), wall),
         (Box("player in the air", 4, 2, 2, 2), floor)]
for p, solid in tests:
    hit = overlaps(p, solid)
    msg = push_out(p, solid) if hit else "no collision"
    print(f"{p.name:25} vs {solid.name:5} hit={hit!s:5}  {msg:26} now at ({p.x:.1f}, {p.y:.1f})")
player falling            vs floor hit=True   pushed up (landed on top)  now at (4.0, 8.0)
player walking into wall  vs wall  hit=True   pushed left                now at (16.0, 5.0)
player in the air         vs floor hit=False  no collision               now at (4.0, 2.0)

The falling player sinks half a unit into the floor and gets pushed up so they stand on top of it. The player walking right gets pushed back left out of the wall. The player in the air touches nothing, so nothing happens. This also connects back to the collision layer we saw in the game maps post, where a tile map marks which tiles are solid. Each solid tile is basically one of these boxes.

Real engines go further. They support circles, capsules and rotated shapes, and they first run a cheap broad phase that throws away pairs of objects that are far apart, before doing exact checks on the few that remain. Checking every object against every other object grows as n squared, which is the kind of cost explained in our Big O notation guide, so skipping pairs early matters a lot on busy levels.

What is the difference between a hitbox and a hurtbox?

This one confused me for years while playing fighting games and shooters. People say the hitbox was wrong, but games usually have several different boxes on the same character. The collision box keeps you from walking through walls and floors. The hitbox is the part that deals damage, like a sword swing or a punch, and it often exists only for a few frames of an attack. The hurtbox is the part of you that can take damage.

Game Dev Series: How Does Game Physics Work? Gravity, Collisions and Hitboxes 5
The collision box handles walls and floors. The hitbox deals damage. The hurtbox receives it.

Damage happens when an attacker’s hitbox overlaps a defender’s hurtbox, using the same overlap test we just wrote. Keeping these boxes separate is what lets a designer make a sword reach a little further than it looks, or shrink a hurtbox so near misses feel fair. In Godot this kind of trigger check is usually done with an Area2D node, which detects overlaps without physically pushing anything.

Why do games use a fixed timestep for physics?

This was the bug where my game behaved differently on different computers. If you run one physics step per rendered frame, a fast PC with 144 frames per second takes many tiny steps, and a slow laptop at 20 frames per second takes a few big ones. Because these simple step formulas are approximations, the results drift apart. Jumps reach different heights and collisions get missed.

The fix is to decouple physics from rendering. The game keeps an accumulator of real time that has passed, and runs physics in fixed slices, for example 1/60 of a second, as many times as needed. Rendering can happen at any frame rate it likes. Glenn Fiedler’s article Fix Your Timestep is the classic write up of this pattern and is worth reading once. Here is a small version that drops a ball for one second at different frame rates.

# Why physics uses a fixed timestep: same fall, different frame rates
GRAVITY = 9.8
FIXED_DT = 1 / 60
def fall_variable(fps, seconds=1.0):
    """Naive: one physics step per rendered frame, dt = 1/fps (explicit Euler)."""
    dt, y, vy = 1 / fps, 0.0, 0.0
    for _ in range(int(fps * seconds)):
        y += vy * dt          # position uses old velocity
        vy += GRAVITY * dt
    return y
def fall_fixed(fps, seconds=1.0):
    """Accumulator: render at any fps, but always step physics at 1/60 s."""
    acc, y, vy, steps = 0.0, 0.0, 0.0, 0
    for _ in range(int(fps * seconds)):
        acc += 1 / fps
        while acc >= FIXED_DT - 1e-9:
            y += vy * FIXED_DT
            vy += GRAVITY * FIXED_DT
            acc -= FIXED_DT
            steps += 1
    return y, steps
print("fps   variable-step fall   fixed-step fall   physics steps")
for fps in (20, 30, 60, 144):
    fy, steps = fall_fixed(fps)
    print(f"{fps:>3}   {fall_variable(fps):10.3f} m          {fy:8.3f} m        {steps}")
print(f"exact answer: {0.5 * GRAVITY * 1.0**2:.3f} m")
fps   variable-step fall   fixed-step fall   physics steps
 20        4.655 m             4.818 m        60
 30        4.737 m             4.818 m        60
 60        4.818 m             4.818 m        60
144        4.866 m             4.818 m        60
exact answer: 4.900 m

With one step per frame, the same one second fall gives a different distance at every frame rate. With the fixed step accumulator, every frame rate takes exactly 60 physics steps and lands on the same answer. It is still slightly off the exact formula because this is a simple approximation, but it is the same on every machine, and that consistency is what players feel. Engines bake this in for you.

Godot runs physics at 60 ticks per second by default, and Unity runs FixedUpdate on a fixed timestep of 0.02 seconds by default.

Game Dev Series: How Does Game Physics Work? Gravity, Collisions and Hitboxes 6
Game Dev Series: How Does Game Physics Work? Gravity, Collisions and Hitboxes 12

Why do fast objects sometimes pass through walls?

This is called tunneling, and every beginner meets it sooner or later. If the game only checks for overlaps at the position an object lands on each step, a fast object can be on one side of a thin wall in one step and fully on the other side in the next. It never overlapped the wall during any single check, so the hit is missed.

Game Dev Series: How Does Game Physics Work? Gravity, Collisions and Hitboxes 7
A discrete check only looks at where the bullet lands. A swept check tests the whole path it travelled during the step.
# Tunneling: a fast bullet can skip right over a thin wall
WALL_X, WALL_W = 47.0, 2.0   # thin wall spans x = 47 to 49
DT = 1 / 60
def discrete_hit(speed):
    x = 0.0
    for _ in range(120):
        x += speed * DT
        if WALL_X <= x <= WALL_X + WALL_W:   # only checks where the bullet lands
            return True
    return False
def swept_hit(speed):
    x = 0.0
    for _ in range(120):
        nx = x + speed * DT
        if x <= WALL_X + WALL_W and nx >= WALL_X:   # checks the whole path this step
            return True
        x = nx
    return False
print("speed (units/s)   move per step   discrete check   swept check")
for speed in (60, 300, 900, 3000):
    print(f"{speed:>15}   {speed*DT:13.1f}   {str(discrete_hit(speed)):>14}   {str(swept_hit(speed)):>11}")
speed (units/s)   move per step   discrete check   swept check
             60             1.0             True          True
            300             5.0            False          True
            900            15.0            False          True
           3000            50.0            False          True

At 60 units per second the bullet moves one unit per step and the plain check catches it. At 300 units per second and above, it jumps right over the thin wall. The swept check tests the whole segment from the old position to the new one, so it catches every case. Unity calls this continuous collision detection and lets you switch it on per Rigidbody for fast objects like bullets.

Many games also simply use a raycast for bullets, which we will look at in the next post.

What tips and tricks help with game physics?

Tune feel, not realism. Most platformers use much stronger gravity than real life, and many add extra gravity when falling so jumps feel snappy.

Keep physics in the fixed update. Movement and collision code belongs in Godot’s _physics_process or Unity’s FixedUpdate, not in the per frame render update.

Turn on collision shape debugging. Godot can show collision shapes while the game runs from the Debug menu. Seeing the boxes solves bugs faster than guessing.

Use simple shapes. Boxes, circles and capsules are cheap and stable. Pixel perfect collision is rarely worth the cost.

Use a character body for players. Godot’s CharacterBody2D guide shows move_and_slide, which handles sliding along walls and floors for you.

Watch out for very fast or very thin things. Thicken walls, cap the maximum speed, or use raycasts and continuous detection for bullets.

Ask AI to explain the step order. When I vibe coded, the real win was understanding why velocity updates before position, not just pasting a movement script.

What common mistakes do beginners make with game physics?

  • Moving objects by a fixed amount per frame without multiplying by delta time, so speed changes with frame rate.
  • Running physics in the render loop, which makes jumps and collisions behave differently on fast and slow machines.
  • Moving a rigid body by setting its position directly, which fights the physics engine and causes jitter.
  • Using one box for everything, so walls, damage and triggers all interfere with each other.
  • Forgetting to resolve the overlap after detecting it, so the player sinks slowly into the floor.
  • Ignoring tunneling until bullets start passing through walls in a fast level.

Frequently asked questions

How does game physics work in simple terms?

Every physics tick, forces like gravity change an object’s velocity, velocity changes its position, and then the engine checks for collisions and fixes any overlaps by pushing, stopping or bouncing objects.

What is AABB collision detection?

AABB stands for axis aligned bounding box. Each object gets a rectangle that does not rotate, and two objects collide only when their boxes overlap on both the x axis and the y axis.

What is the difference between a hitbox and a hurtbox?

A hitbox is the area that deals damage, such as a sword swing. A hurtbox is the area of a character that can receive damage. Damage happens when a hitbox overlaps a hurtbox.

Why do games use a fixed timestep for physics?

A fixed timestep runs physics in equal slices, such as 1/60 of a second, regardless of frame rate. This keeps jumps, speeds and collisions consistent on fast and slow computers.

Why do fast objects go through walls in games?

This is called tunneling. A fast object can move past a thin wall between two checks. Swept tests, continuous collision detection or raycasts fix it by checking the whole path.

That is how I now picture game physics. A loop that nudges velocity and position a little every tick, boxes that check for overlaps, and a few clever tricks so fast things and slow computers still behave. Next in the Game Dev Series we look at how bullets and weapons work, with projectiles, raycasts and cooldowns, and then move on to sound and enemy AI.

Content Protection by DMCA.com
Spread the love
Scroll to Top
×