Camera Follow Mouse Issue

Hello Unity Community!

This is my first post on here, so I hope I format and explain everything correctly.

I’m making a very simple game of 5 cars. As you move your mouse from left to right, you see the different cars. I am using the following script on my camera, in JavaScript.

#pragma strict

public var mouseSensitivity : float = 0.01;
private var lastPosition : Vector3;

function Start() {
    lastPosition = Input.mousePosition;

 function Update() {
	 var delta : Vector3 = Input.mousePosition - lastPosition;
     transform.Translate(delta.x * mouseSensitivity, 0, 0);
     lastPosition = Input.mousePosition;

This script works fine, but it assumes the user will start the game off in the middle of the screen. If, for example, the game starts and the users mouse is on the far left of the screen, the above script will calculate that and have everything off when scrolling.

For example, if the user’s mouse starts in the middle the far right looks like the following:

But if it starts off on the far left, the far right it looks like this:

My knowledge of Unity is very little, and am trying to crawl my way up the learning curve.

Does anybody know how I can improve my script to work around this? (Besides adding a “Start button” in the middle of my screen.)

Thank you!

Well, I suppose there are a lot of ways to fix this.

Easiest way would be to change this line:

function Start()
    lastPosition = Input.mousePosition;

to this:

function Start()
    lastPosition = Vector3(Screen.width / 2, Screen.height / 2,0);

Though that way, the user might not start in the middle of the screen. If you want it to start in the center, then clamping the camera between a min and a max value should work. Like this:

public var mouseSensitivity : float = 1;
public var minX : float = 0;
public var maxX : float = 50;
function Update()
    var delta : float = Input.GetAxis("Mouse X") * mouseSensitivity; // Using this we can continue moving left/right when we hit the side of the screen

    var newPosition : Vector3 = transform.position;
    newPosition.x = Mathf.Clamp(transform.position.x + delta,minX, maxX);
    transform.position = newPosition;

The difference with your current scipt here is that the user might be able to continue to scroll as long as the camera hasen’t reached minX or maxX, even when the mouse has reached the far left/right side of the sreen.