Skip to content

Instantly share code, notes, and snippets.

@rsaenzi
Last active May 5, 2024 17:40
Show Gist options
  • Save rsaenzi/fc484311c795fbbd6a861dcfd1075e2b to your computer and use it in GitHub Desktop.
Save rsaenzi/fc484311c795fbbd6a861dcfd1075e2b to your computer and use it in GitHub Desktop.
Script for Unity to add Drag and Drop support for 2D/3D objects
//
// DragAndDrop.cs
//
// Created by Rigoberto Sáenz Imbacuán (https://linkedin.com/in/rsaenzi/)
// Copyright © 2021. All rights reserved.
//
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Collider))]
public class DragAndDrop : MonoBehaviour {
// The plane the object is currently being dragged on
Plane dragPlane;
// The difference between where the mouse is on the drag plane and
// where the origin of the object is on the drag plane
Vector3 offset;
Camera myMainCamera;
void Start() {
myMainCamera = Camera.main;
}
void OnMouseDown() {
dragPlane = new Plane(myMainCamera.transform.forward, transform.position);
Ray camRay = myMainCamera.ScreenPointToRay(Input.mousePosition);
float planeDist;
dragPlane.Raycast(camRay, out planeDist);
offset = transform.position - camRay.GetPoint(planeDist);
}
void OnMouseDrag() {
Ray camRay = myMainCamera.ScreenPointToRay(Input.mousePosition);
float planeDist;
dragPlane.Raycast(camRay, out planeDist);
transform.position = camRay.GetPoint(planeDist) + offset;
}
}
@ilywkaa
Copy link

ilywkaa commented Feb 3, 2023

Thank you so much!
Solved the problem of mesh items drag&drop inventory mechanics

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment