Click and Drag Camera

So I’ve created a simple camera script to click and drag the game view around. Using the left mouse button to click inside the game it “grabs” the ground and then calculates the difference between where you clicked and where you moved the mouse to, then moves the cameras position accordingly to simulate it all. The problem i’m having is that because i’m using ScreenToViewportPoint to calcuate this (I couldn’t get ScreenToWorldPoint to work) every time I click it moves the camera back to 0,0,0. So everything works great as long as I don’t need to click to drag more than one time… I’ve tried tons of things and can’t get anything to work. Here’s my code:

	void MousePan()
	{
		if(Input.GetMouseButtonDown(0))
		{
			panOrigin = Camera.main.ScreenToViewportPoint(Input.mousePosition);					//Get the ScreenVector the mouse clicked
		}

		if(Input.GetMouseButton(0))
		{
			Vector3 pos = Camera.main.ScreenToViewportPoint(Input.mousePosition) - panOrigin;	//Get the difference between where the mouse clicked and where it moved
			transform.position = -pos * panSpeed; 												//Move the position of the camera to simulate a drag, speed * 10 for screen to worldspace conversion
		}
	}

Figured it out:

		if(Input.GetMouseButtonDown(0))
		{
			bDragging = true;
			oldPos = transform.position;
			panOrigin = Camera.main.ScreenToViewportPoint(Input.mousePosition);					//Get the ScreenVector the mouse clicked
		}

		if(Input.GetMouseButton(0))
		{
			Vector3 pos = Camera.main.ScreenToViewportPoint(Input.mousePosition) - panOrigin;	//Get the difference between where the mouse clicked and where it moved
			transform.position = oldPos + -pos * panSpeed; 										//Move the position of the camera to simulate a drag, speed * 10 for screen to worldspace conversion
		}

		if(Input.GetMouseButtonUp(0))
		{
			bDragging = false;
		}

This is also a very good solution

Panning with using Mouse axes from input manager using Input.GetAxis().

You can inverse the pan direction by removing the minus character from transfrom.Translate()-method.

Also you may want to use z axis instead of y depending on your configuration.

public class CameraScript : MonoBehaviour
{
    public float panSpeed = 10f;
    
    void Update()
    {
        if (Input.GetMouseButton(1)) // right mouse button
        {
            var newPosition = new Vector3();
            newPosition.x = Input.GetAxis("Mouse X") * panSpeed * Time.deltaTime;
            newPosition.y = Input.GetAxis("Mouse Y") * panSpeed * Time.deltaTime;

            // translates to the opposite direction of mouse position.
            transform.Translate(-newPosition);
        }
    }

}