Created
March 22, 2014 19:17
-
-
Save r3econ/9712710 to your computer and use it in GitHub Desktop.
Unity 3D Click & Drag Behavior.
This file contains 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 DragBehavior : MonoBehaviour | |
{ | |
private Vector3 screenPoint; | |
private Vector3 offset; | |
void OnMouseDown () | |
{ | |
// Get the click location. | |
screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position); | |
// Get the offset of the point inside the object. | |
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, | |
Input.mousePosition.y, | |
screenPoint.z)); | |
} | |
void OnMouseDrag () | |
{ | |
// Get the click location. | |
Vector3 newScreenPoint = new Vector3(Input.mousePosition.x, | |
Input.mousePosition.y, | |
screenPoint.z); | |
// Adjust the location by adding an offset. | |
Vector3 newPosition = Camera.main.ScreenToWorldPoint(newScreenPoint) + offset; | |
// Assign new position. | |
transform.position = newPosition; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey, is it cool if I use this in my project?