Drag a 3-D object using mouse unity| Leran unity | Drag in unity | Unity screen to world tutorial
In this video i have shown how to drag a 3-D object using mouse in unity
Code :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
- Attach this script on that gameObject which you want to drag.Note: That gameObject must have a
collider on it.
- This script selects and drags/moves an object in world space i.e 3-d space .
Logic:
1. Player is dragged according to position of cursor (OnMouseDrag).
*/
public class Drag : MonoBehaviour
{
private Vector3 screenPoint;
private Vector3 offset;
void OnMouseDown(){
screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}
void OnMouseDrag(){
Vector3 cursorPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 cursorPosition = Camera.main.ScreenToWorldPoint(cursorPoint) + offset;
transform.position = cursorPosition;
}
}