Camera Pan not working correctly

Hi Guys,

I have a script, just a modification of the orbit camera navigation script. I am trying to pan. I have been able to pan but every time I use another button such as rotate, the position of the object pops back to the center of the screen.

Why is this happening? How can i write it so the object stays in place once I pan and then try and rotate?

var target : Transform;
var distance = 80.0;

var xSpeed = 450.0;
var ySpeed = 120.0;
var mindistance = 20;
var maxdistance = 80;
var moveSpeed : float = 0.05f;

var yMinLimit = -20;
var yMaxLimit = 120;

private var x = 0.0;
private var y = 0.0;
@script AddComponentMenu("Camera-Control/Mouse Orbit")



function Start () {
    var angles = transform.eulerAngles;
    x = angles.y;
    y = angles.x;

	// Make the rigid body not change rotation
   	if (rigidbody)
		rigidbody.freezeRotation = true;
}

function LateUpdate () {
//function Update() {    
    if (Input.GetMouseButton(0))
    {
	    if (target) {
	        x += Input.GetAxis("Mouse X") * xSpeed * 0.02;
	        y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02;
	 		
	 		y = ClampAngle(y, yMinLimit, yMaxLimit);
	 		       
	        var rotation = Quaternion.Euler(y, x, 0);
	        var position = rotation * Vector3(0.0, 0.0, -distance) + target.position;
	        
	        transform.rotation = rotation;
	        transform.position = position;
	    }
   	}

	if (Input.GetAxis("Mouse ScrollWheel") < 0) // back
	{
	// First we add a value to the existing fov distance
	camera.fov += 10;
	// then we clamp it. by giving it a min and max value
	camera.fov = Mathf.Clamp(camera.fov, mindistance, maxdistance);
	}
	
	if (Input.GetAxis("Mouse ScrollWheel") > 0) // forward
	{
	//distance += 10;
	camera.fov -= 10;
	camera.fov = Mathf.Clamp(camera.fov, mindistance, maxdistance);
	}
	
	if (Input.GetMouseButton(2)) 
	{ 
	//transform.rotation = camera.rotation; 
	transform.Translate(transform.right * -Input.GetAxis("Mouse X") * moveSpeed); 
	transform.Translate(transform.up * -Input.GetAxis("Mouse Y") * moveSpeed, Space.World);
	}
    
}

static function ClampAngle (angle : float, min : float, max : float) {
	if (angle < -360)
		angle += 360;
	if (angle > 360)
		angle -= 360;
	return Mathf.Clamp (angle, min, max);
}

It’s because you reset the position during rotation with these lines:

var position = rotation * Vector3(0.0, 0.0, -distance) + target.position;

transform.position = position;

If you want to keep the position after panning but still orbit you need to decide how to handle it, since it’s not that clear what it should do if you pan over to one side and aren’t even pointing at the object and then start rotating around it. I guess when you start orbiting after panning you could snap the camera angle back to point at the original target, recalculate the “distance” var based on your new distance from the target, and then calculate the new x and y.