Skip to content

Instantly share code, notes, and snippets.

@r3econ
Created March 22, 2014 19:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save r3econ/9712710 to your computer and use it in GitHub Desktop.
Save r3econ/9712710 to your computer and use it in GitHub Desktop.
Unity 3D Click & Drag Behavior.
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;
}
}
@jmbeach
Copy link

jmbeach commented Nov 26, 2015

Hey, is it cool if I use this in my project?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment