#Drag and Drop Orthographic
1 messages · Page 1 of 1 (latest)
public class DragandDrop : MonoBehaviour
{
Vector3 mousePosition;
private Vector3 GetMousePos(){
return Camera.main.WorldToScreenPoint(transform.position);
}
private void OnMouseDown(){
mousePosition = Input.mousePosition - GetMousePos();
}
private void OnMouseDrag(){
transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition - mousePosition);
}
This was the code used
Make a plane with new Plane(Vector3.up, transform.position) and raycast to the plane. There's an example in the documentation that can be adapted: https://docs.unity3d.com/ScriptReference/Plane.Raycast.html
Okay, let me try that, thank you
private Vector3 offset;
private float initialY;
void OnMouseDown()
{
initialY = transform.position.y;
Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.WorldToScreenPoint(transform.position).z));
offset = transform.position - mouseWorldPos;
}
void OnMouseDrag()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Plane plane = new Plane(Vector3.up, new Vector3(0, initialY, 0)); // Plane at initial Y
float distance;
if (plane.Raycast(ray, out distance))
{
Vector3 pointOnPlane = ray.GetPoint(distance);
transform.position = new Vector3(pointOnPlane.x + offset.x, initialY, pointOnPlane.z + offset.z);
}
}