Move Camera by drag

Hello,

Working on a 2D Unity and I stumbled upon moving the camera around that I want to do by dragging anywhere on the screen and upon moving the cursor, the camera follows its movement.

This is what I tried:

  • Made a MouseState struct

    struct MouseState
    {
    public bool LeftButton;
    public Vector2 Position;
    }

  • Checked each Update() for the following:

    MouseState OldMS, NewMS;
    public Camera TargetCam;

     void Update()
     {
         OldMS.LeftButton = NewMS.LeftButton;
         OldMS.Position = NewMS.Position;
         NewMS.LeftButton = Input.GetMouseButtonDown(0);
         NewMS.Position = Input.mousePosition;
    
         if (OldMS.LeftButton && NewMS.LeftButton)
         {
             int DeltaX = (int)(OldMS.Position.x - NewMS.Position.x);
             int DeltaY = (int)(OldMS.Position.y - NewMS.Position.y);
             TargetCam.transform.Translate(new Vector3(DeltaX, DeltaY));
    
         }
     }
    

Yet I do not achieve the wanted result. Halp…

1 Answer

1

If you have a standard 2D setup…orthographic camera with a rotation of (0,0,0)…this script will, attached to the camera, will drag. With minor modifications, you can put it on another game object like you are doing in your script.

using UnityEngine;
using System.Collections;

// Attach to orthographic camera with rotation (0,0,0)
public class DragOrthoCamera : MonoBehaviour {

	private Vector3 startMousePos;

	void Update() {
		if (Input.GetMouseButtonDown (0)) {
			startMousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
			startMousePos.z = 0.0f;
		}

		if (Input.GetMouseButton (0)) {
			Vector3 nowMousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
			nowMousePos.z = 0.0f;
			transform.position += startMousePos - nowMousePos;
		}
	}
}