I am making a level editor within my game and I wanted to be able to pan the camera around much like Unity does when you hold down the middle mouse button in the scene view. The editor is an orthographic view as it is a 2D platforming game. I found a lot of examples but they were all fairly imprecise, I am looking for something more accurate. This is my current attempt at it:
//mouse pan
if (Input.GetMouseButtonDown(2))
{
dragPos = new Vector2(camera.ScreenToWorldPoint(Input.mousePosition).x, camera.ScreenToWorldPoint(Input.mousePosition).y);
startPos = transform.position;
}
if (Input.GetMouseButtonUp(2))
{
dragPos = Vector2.zero;
}
if (dragPos != Vector2.zero)
{
transform.position = startPos + (dragPos - new Vector2(camera.ScreenToWorldPoint(Input.mousePosition).x, camera.ScreenToWorldPoint(Input.mousePosition).y));
}
It seems to almost work, but it tends to make the camera jerk around a lot. Any suggestions?
~Thank you Unity Community
Although this is an older thread, it showed up on the front page of a google search I just did so I figured I would reply with my fix. This code also includes mouse wheel zoom in and out on an orthographic camera.
using UnityEngine;
using System.Collections;
/// <summary>
/// This class will control camera movement in the Tool Scene
/// </summary>
public class ToolSceneCameraControl : MonoBehaviour
{
float sizeMin = 2f;
float sizeMax = 35f;
Camera cam;
Vector3 prevWorldPos, curWorldPos, worldPosDelta;
// Use this for initialization
void Start ()
{
cam = GetComponent<Camera>();
}
// Update is called once per frame
void Update ()
{
//Handles mouse scroll wheel input to modify the zoom of the camera
cam.orthographicSize = Mathf.Clamp(cam.orthographicSize - Input.mouseScrollDelta.y, sizeMin, sizeMax);
//Handles middle mouse button panning.
//Sets the previous vectors to what is current because we are restarting the panning chain of events.
if (Input.GetMouseButtonDown(2))
{
prevWorldPos = cam.ScreenToWorldPoint(Input.mousePosition);
}
if (Input.GetMouseButton(2))
{
//Gets the delta of the worldPos and mousePos
worldPosDelta = cam.ScreenToWorldPoint(Input.mousePosition) - prevWorldPos;
cam.transform.position = new Vector3(cam.transform.position.x - worldPosDelta.x, cam.transform.position.y - worldPosDelta.y, cam.transform.position.z);
//Set previous variables to current state for use in next frame
prevWorldPos = cam.ScreenToWorldPoint(Input.mousePosition);
}
}
}