# Restrict user driven camera movement to a cubic area?

What’s the easiest way from my animation loop to restrict the movement of the camera, driven by the user’s keyboard and mouse, to an area defined by a cube?

In other words, in my code that converts keyboard and mouse changes to camera position changes, how can I easily detect when the camera is “touching” the boundary of an area defined by a cube (i.e. - fence them in)?.

So, there is no cube object in the world that I want to restrict movement inside, I just want to prevent the camera from exiting the boundaries of a predefined cubic area. Any code samples I can look at?

This might help Box3 – three.js docs (threejs.org).

1 Like

Even if there is no cube object in your scene, you could create one, make it `BackSide` and invisible, and use it for your purpose - that’s just one possibility, of course, and it would involve checking if the camera is outside the cube, translating the camera back (or inside the cube) on its direction (Z), getting its position and direction, use a raycaster to get the intersect point with the cube and then translating the camera forward to the intersect point aka the point you want it to stop.

I could share the “restrict movement outside” code I use, but it would probably need some adjustments for your case and there’s an easier way anyway. Since you’re talking about an imaginary cube and it’s a simple shape, the easiest way would be to just perform the movement in your key and pointer event listeners only if the camera position is within the space between the cube’s sides, i.e. in pseudo-code:

``````if (camera.position.x + cameramovementx >= cubeleftsidex &&
camera.position.x + cameramovementx <= cuberightsidex &&
camera.position.y + cameramovementy >= cubebottomsidey &&
camera.position.y + cameramovementy <= cubetopsidey &&
camera.position.z + cameramovementz >= cubebacksidez &&
camera.position.z + cameramovementz >= cubefrontsidez)
{
Or, you can follow @anidivr advice and use the `.clampPoint()`, `.containsPoint()` and `.distanceToPoint()` to test and restrict the point (i.e. camera position) within the said box.