Last active
May 5, 2024 17:40
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you so much!
Solved the problem of mesh items drag&drop inventory mechanics