Premium Features

Download Video

Hitbox implementation

Our player sprite has padding around it for attack animations, but collision detection should only consider the character's body. In this lesson, we'll implement a hitbox—a smaller collision area separate from the visual sprite.

The Problem

The sprite image is larger than the character to accommodate animations. Using the full image for collision makes the player float above platforms or collide with invisible air.

A hitbox is the actual collision boundary. It's often smaller than the visual sprite and positioned precisely around the character's body.

Defining the Hitbox

Add a hitbox property to the Player class:

// In Player update method this.hitbox = {   position: {     x: this.position.x + 58,  // Offset from sprite edge     y: this.position.y + 34   },   width: 50,   height: 54 }

Visualizing the Hitbox

During development, draw the hitbox to fine-tune its position:

// Debug visualization c.fillStyle = 'rgba(0, 255, 0, 0.3)' c.fillRect(   this.hitbox.position.x,   this.hitbox.position.y,   this.hitbox.width,   this.hitbox.height )

Updating Collision Detection

Replace references to player position/dimensions with hitbox values:

// Before (using sprite bounds) if (collision({ object1: this, object2: block }))  // After (using hitbox) if (collision({ object1: this.hitbox, object2: block }))

Repositioning After Collision

When a collision is detected, reposition based on the hitbox, then update the sprite position accordingly:

// Collision on right side const offset = this.hitbox.position.x - this.position.x this.position.x = block.position.x - this.hitbox.width - offset - 0.01

Why This Matters

Hitboxes create that satisfying "fair" feeling in platformers. The player sees exactly where they can and can't go, and collisions match visual expectations.

Comments

Want to participate?

Create a free Chris Courses account to begin

Login

No comments yet, be the first to add one

Providing the lift to launch your development career

© 2026 Chris Courses. All rights reserved.