Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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