Limit Camera Movement on XY Axis

var mDelta = 10; // Pixels. The width border at the edge in which the movement work
var mSpeed = 30.0; // Scale. Speed of the movement
var xSensitivity = 20.0;
var ySensitivity = 20.0;

function LateUpdate ()
{

      // Check if on the right edge
   if ( Input.mousePosition.x >= Screen.width - mDelta )
   {
      // Move the camera
      transform.position += transform.right * Time.deltaTime * mSpeed;
   }


   if ( Input.mousePosition.x <= 0 + mDelta )
   {
      // Move the camera
      transform.position -= transform.right * Time.deltaTime * mSpeed;
   }


   if ( Input.mousePosition.y >= Screen.height - mDelta )
   {
      // Move the camera
      transform.position += transform.forward * Time.deltaTime * mSpeed;
   }

   if ( Input.mousePosition.y <= 0 + mDelta )
   {
      // Move the camera
      transform.position -= transform.forward * Time.deltaTime * mSpeed;
   }


    // Changing an angle, if mouse button is held   
    if (Input.GetMouseButton(1) )
    {
      // Update x, y angle with the mouse delta
      xAngleChange = Input.GetAxis ("Mouse X") * xSensitivity * Time.deltaTime;
      yAngleChange = Input.GetAxis ("Mouse Y") * ySensitivity * Time.deltaTime;

      // Rotate around the current up direction by the delta mouse x
transform.rotation = transform.rotation *
         Quaternion.Euler(-yAngleChange, xAngleChange, 0); 
   }
}

this is my code for my camera movement…how to set a limit in the X and Y axis? Now the camera can keep scrolling infinity…I want to set the camera to move within an area only.

Example: when i have a 300 x 300 box, the camera can only move around that box, not outside the box :slight_smile:

Simplest way is to use Clamp:

transform.position.x = Mathf.Clamp(-100, 100);

Thanks, i’ll try to experiment it. By the way, is there any example that i can look at ?

EDIT: Thanks its working now, need to add transform.position.x inside the bracket.

transform.position.x = Mathf.Clamp(transform.position.x,-10, 10);

:slight_smile:

Hi! I have problem with camera 2d.

  1. I have a big map and camera screen smaller than map.
  2. I want camera move follow the player and player always center of the camera screen, but if the camera move to the end of right map or bottom of the map or top of the map, the camera will not move follow the player , player can move to the end of right map without move camera.
    This is my script:

var cam = Camera.main.transform;
if(transform.position.x >= -20 transform.position.x <= 20 || transform.position.y <= 18.5 transform.position.y >= 0 ){
cam.parent=transform;
}
else{
cam.parent = null;
}

some pic :