Last active
September 17, 2015 09:15
-
-
Save grimmdev/e39731d56074571ddf9f to your computer and use it in GitHub Desktop.
I made this myself, I wanted to give it a shot and I needed a simple yet customized solution for Camera Dragging.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
public class CameraDragController : MonoBehaviour { | |
public Transform Target; | |
public float Sensitivity = 0.1f; | |
public bool Invert = false; | |
public bool Hold = false; | |
public Rect Bounds; | |
private Vector3 TargetStart = Vector3.zero; | |
private Vector3 MouseStart = Vector3.zero; | |
private Vector3 TargetPosition = Vector3.zero; | |
private Vector3 MousePosition = Vector3.zero; | |
// Use this for initialization | |
void Awake () | |
{ | |
} | |
// Update is called once per frame | |
void Update () | |
{ | |
if (Hold) { | |
HoldDrag (); | |
} else { | |
Drag (); | |
} | |
} | |
private void HoldDrag() | |
{ | |
if (Input.GetMouseButtonDown(0)) | |
{ | |
MouseStart = Input.mousePosition; | |
return; | |
} | |
if (!Input.GetMouseButton(0)) return; | |
Vector3 pos = Camera.main.ScreenToViewportPoint (Input.mousePosition - MouseStart); | |
Vector3 move = new Vector3(pos.x * Sensitivity, pos.y * Sensitivity, 0); | |
if (Invert) { | |
Target.Translate (-move, Space.World); | |
} else { | |
Target.Translate (move, Space.World); | |
}; | |
TargetPosition = Target.position; | |
TargetPosition.x = Mathf.Clamp (TargetPosition.x, Bounds.xMin, Bounds.xMax); | |
TargetPosition.y = Mathf.Clamp (TargetPosition.y, Bounds.yMin, Bounds.yMax); | |
Target.position = TargetPosition; | |
} | |
private void Drag() | |
{ | |
TargetPosition = Target.position; | |
if (Input.GetMouseButtonDown(0)) | |
{ | |
MouseStart = Input.mousePosition; | |
TargetStart = TargetPosition; | |
return; | |
} | |
if (!Input.GetMouseButton(0)) return; | |
MousePosition = MouseStart - Input.mousePosition; | |
if (Invert) { | |
TargetPosition = TargetStart - (MousePosition * Sensitivity); | |
} else { | |
TargetPosition = TargetStart + (MousePosition * Sensitivity); | |
}; | |
TargetPosition.x = Mathf.Clamp (TargetPosition.x, Bounds.xMin, Bounds.xMax); | |
TargetPosition.y = Mathf.Clamp (TargetPosition.y, Bounds.yMin, Bounds.yMax); | |
TargetPosition.z = TargetStart.z; | |
Target.position = TargetPosition; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment