Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[Unity3DObjectDragHandler.cs] Handles drag and drop for a 3D object in Unity3D #unity #csharp #draganddrop
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