Hitbox Visualization
Learn about hitbox visualization
Hitbox Visualization
What is hitbox visualization?
Hitbox visualization displays collision boundaries on screen so you can see and debug collision detection in real-time.
Benefits of hitbox visualization?
- Debug collision detection
- Visualize hitbox boundaries
- Test collision accuracy
- Adjust hitbox size
- Improve collision logic
// Draw hitboxes for debugging
function drawHitbox(ctx, object, debug = true) {
if (!debug) return;
// Draw transparent rectangle for hitbox
ctx.strokeStyle = '#00ff00';
ctx.lineWidth = 2;
ctx.globalAlpha = 0.5;
ctx.strokeRect(
object.x,
object.y,
object.width,
object.height
);
ctx.globalAlpha = 1.0;
// Label the hitbox
ctx.fillStyle = '#00ff00';
ctx.font = '12px Arial';
ctx.fillText(object.name, object.x, object.y - 5);
}
// Usage
const gameObjects = [
{ name: 'player', x: 100, y: 300, width: 50, height: 50 },
{ name: 'enemy', x: 200, y: 300, width: 50, height: 50 }
];
// Draw all hitboxes
gameObjects.forEach(obj => drawHitbox(ctx, obj, true));
What does this code do?
- Draws green rectangles around game objects
- Uses transparency for better visibility
- Labels each hitbox with object name
- Shows hitbox boundaries on canvas
- Helps debug collision detection
- Can be toggled on/off with debug flag
// Collision detection with visual debugging
function checkCollision(obj1, obj2, ctx, debugDraw = true) {
// Calculate collision
const colliding = !(
obj1.x + obj1.width < obj2.x ||
obj1.x > obj2.x + obj2.width ||
obj1.y + obj1.height < obj2.y ||
obj1.y > obj2.y + obj2.height
);
// Debug visualization
if (debugDraw) {
const color = colliding ? '#ff0000' : '#00ff00';
// Draw both objects
ctx.strokeStyle = color;
ctx.lineWidth = 3;
ctx.strokeRect(obj1.x, obj1.y, obj1.width, obj1.height);
ctx.strokeRect(obj2.x, obj2.y, obj2.width, obj2.height);
// Draw collision info
ctx.fillStyle = color;
ctx.font = '14px Arial';
if (colliding) {
ctx.fillText('COLLISION!', 10, 20);
}
}
return colliding;
}
What does this code do?
- Checks if two objects collide
- Draws red box if collision occurs, green if not
- Shows both object boundaries
- Displays “COLLISION!” text when objects touch
- Helps debug collision detection
- Shows visual debugging in action
Try It Yourself
%%js // CODE_RUNNER: hitbox-visualization function checkCollision(rect1, rect2) { return !(rect1.x + rect1.width < rect2.x || rect1.x > rect2.x + rect2.width || rect1.y + rect1.height < rect2.y || rect1.y > rect2.y + rect2.height); }
const player = { x: 50, y: 50, width: 40, height: 40 }; const enemy = { x: 60, y: 60, width: 40, height: 40 }; const colliding = checkCollision(player, enemy); console.log(“Collision detected: “ + colliding);