- Home /
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:
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..
Answer by robertbu · Oct 20, 2014 at 10:49 PM
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;
}
}
}
Your answer
Follow this Question
Related Questions
Is it good idea to implement camera drag with UI drag event? 2 Answers
Drag camera: Translate and DeltaPosition: move object a little further at end [ANDROID] 0 Answers
Make object follow mouse, while actually moving camera, instead of object 2 Answers
How do I swipe on a texture and know if its swiped 100% 1 Answer
NGUI: Draggable Camera and Scroll Panel 0 Answers