Limit Object Position in Three.js with MathUtils.clamp

Keeping 3D objects within a specific boundary is a common requirement in interactive web applications and game development. This article explains how to use the MathUtils.clamp function in Three.js to restrict a moving object’s position coordinates, ensuring it remains within predefined minimum and maximum limits.

The MathUtils.clamp function is a built-in utility in Three.js that takes three parameters: the current value to restrict, the minimum allowed value, and the maximum allowed value. If the current value falls below the minimum, the function returns the minimum limit. If it exceeds the maximum, it returns the maximum limit. Otherwise, it returns the current value unchanged.

The basic syntax for the function is:

THREE.MathUtils.clamp(value, min, max);

To restrict a moving object within a 3D bounding area, you apply this function to the object’s position coordinates (X, Y, or Z) inside your render or animation loop. This ensures the boundaries are enforced on every frame as the object moves.

Below is a practical code example demonstrating how to restrict an object’s X and Y positions within a defined boundary:

// Define the boundary limits
const minX = -10, maxX = 10;
const minY = -5, maxY = 5;

// Inside your animation/update loop
function animate() {
    requestAnimationFrame(animate);

    // 1. Update the object's position (e.g., via keyboard input, physics, or velocity)
    cube.position.x += velocity.x;
    cube.position.y += velocity.y;

    // 2. Clamp the positions to restrict them within the boundaries
    cube.position.x = THREE.MathUtils.clamp(cube.position.x, minX, maxX);
    cube.position.y = THREE.MathUtils.clamp(cube.position.y, minY, maxY);

    renderer.render(scene, camera);
}

In this implementation, even if the movement velocity continuously pushes the object outward, the cube.position coordinates will never exceed the specified minimum and maximum ranges. This is an efficient and clean way to prevent players, cameras, or interactive elements from drifting off-screen or passing through invisible boundaries in a Three.js scene.