Camera Follow Mouse

Hi there

I’ve got this piece of code for my camera (thanks to @simco500) to look around the player, according to the mouse position. It works like a charm, except I can’t adjust how far the camera can travel. Simpy put, I’d like to give it boundaries/tell it how far out it can go. Could anyone help me out?

#pragma strict

 var Damping = 6.0;
 var Player : Transform;
 var Height : float = 13.0;
 var Offset : float = 0.0;
 
 private var Center : Vector3;
 
 function Update () 
 {
     var mousePos = Input.mousePosition;
     var CursorPosition : Vector3 = Camera.main.ScreenToWorldPoint(mousePos);
     
     var PlayerPosition = Player.position;
     
     Center = Vector2((PlayerPosition.x + CursorPosition.x) / 2, (PlayerPosition.y + CursorPosition.y) / 2);
     
     transform.position = Vector3.Lerp(transform.position, Center + Vector3(0,Height,Offset), Time.deltaTime * Damping);
 }

Here’s a shot of just how way too far it travels.

Cheers!

I would change this part:

Center = Vector2((PlayerPosition.x + CursorPosition.x) / 2, (PlayerPosition.y + CursorPosition.y) / 2);

Add these definitions:

var changex : float = 0.0;
var changey : float = 0.0;
var limitx : int = 100;
var limity : int = 100;

And make it like this:

changex = (PlayerPosition.x + CursorPosition.x) / 2;
changey = (PlayerPosition.y + CursorPosition.y) / 2;
if (changex > limitx) { changex = limitx; }
if (changey > limity) { changey = limity; }
Center = Vector2(changex, changey);

Just use Mathf.Clamp to limit your center’s position.

float horizontalLimit = 1f;

float verticalLimit = 1f;

Center.x = Mathf.Clamp(Center.x, -horizontalLimit, horizontalLimit);
Center.y = Mathf.Clamp(Center.y, -verticalLimit, verticalLimit);