how to drag 2d object unity code example
Example 1: how to get 2D object drag with mouse unity
private Vector3 screenPoint;
private Vector3 offset;
void OnMouseDown() {
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}
void OnMouseDrag()
{
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
transform.position = curPosition;
}
}
Example 2: 2d item dragging unity
public class followMouse : MonoBehaviour
{
bool canDrag = false;
Vector3 itemPos;
void Update()
{
transform.position = Input.mousePosition;
if (!Input.GetMouseButton(0))
{
canDrag = false;
}
}
void OnTriggerStay2D(Collider2D other)
{
if (other.CompareTag("itemIcon"))
{
if (Input.GetMouseButton(0))
{
canDrag = true;
other.transform.position = Input.mousePosition;
}
}
}
}