Skip to content

Instantly share code, notes, and snippets.

@OutlawGameTools
Created November 21, 2015 02:40
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 OutlawGameTools/5947d54e3effecb53fcc to your computer and use it in GitHub Desktop.
Save OutlawGameTools/5947d54e3effecb53fcc to your computer and use it in GitHub Desktop.
Drag a 2D game object using the mouse. Game Object must have a Collider2D component.
using UnityEngine;
using System.Collections;
public class DragWithMouse : MonoBehaviour {
private Vector3 offset;
void OnMouseDown () {
Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0);
offset = transform.position - Camera.main.ScreenToWorldPoint(mousePos);
}
void OnMouseDrag () {
Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0);
transform.position = Camera.main.ScreenToWorldPoint(mousePos) + offset;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment