Last active
January 15, 2023 23:34
-
-
Save fardjad/0a344b19d7288f1ab4e9b67c16e608e0 to your computer and use it in GitHub Desktop.
[Unity3DObjectDragHandler.cs] Handles drag and drop for a 3D object in Unity3D #unity #csharp #draganddrop
This file contains hidden or 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
using UnityEngine; | |
public class Unity3DObjectDragHandler : MonoBehaviour | |
{ | |
public Camera camera; | |
public void Start() | |
{ | |
} | |
public void Update() | |
{ | |
if (camera == null) return; | |
if (Input.touchCount > 0) | |
{ | |
var touch = Input.GetTouch(0); | |
if (touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary) | |
{ | |
var touchPosition = touch.position; | |
var rayFromCameraPassingThroughTouchPosition = camera.ScreenPointToRay(touchPosition); | |
// Create a logical plane at this object's position and perpendicular to world Y | |
var planeInCurrentObjectPosition = new Plane(Vector3.up, transform.position); | |
if (planeInCurrentObjectPosition.Raycast(rayFromCameraPassingThroughTouchPosition, out var distance)) | |
{ | |
var hitPos = rayFromCameraPassingThroughTouchPosition.GetPoint(distance); | |
transform.position = hitPos; | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment