Skip to content

Instantly share code, notes, and snippets.

@haramakoto
Forked from SimonDarksideJ/MakeA3DObjectDraggable.cs
Last active December 31, 2021 22:41
Show Gist options
  • Save haramakoto/3676a5fb911b16166018774d6b30a636 to your computer and use it in GitHub Desktop.
Save haramakoto/3676a5fb911b16166018774d6b30a636 to your computer and use it in GitHub Desktop.
How to make a 3D object draggable in Unity3D
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
/*
MAKE A 3D OBJECT DRAGGABLE
Riccardo Stecca
http://www.riccardostecca.net
https://github.com/rstecca
And check out UNotes here: https://github.com/rstecca/UNotes
!!! Remember that in order to get this working you need a PhysicsRaycaster on the current camera. !!!
*/
/*
ドラッグ開始時にオブジェクトがずれないように改変
*/
[RequireComponent(typeof(Collider))]
public class MakeA3DObjectDraggable : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler {
Camera m_cam;
Vector3 m_Sabun;
void Start () {
if (Camera.main.GetComponent<PhysicsRaycaster>() == null)
Debug.Log("Camera doesn't ahve a physics raycaster.");
m_cam = Camera.main;
}
public void OnDrag(PointerEventData eventData)
{
Vector3 pos = GetMouseRayPosition() + m_Sabun;
transform.position = pos;
}
public void OnBeginDrag(PointerEventData eventData)
{
m_Sabun = transform.position - GetMouseRayPosition();
if(GetComponent<Rigidbody>()!=null)
{
GetComponent<Rigidbody>().isKinematic = true;
}
}
Vector3 GetMouseRayPosition()
{
Ray R = m_cam.ScreenPointToRay(Input.mousePosition);
Vector3 PO = transform.position; // Take current position of this draggable object as Plane's Origin
Vector3 PN = -m_cam.transform.forward; // Take current negative camera's forward as Plane's Normal
float t = Vector3.Dot(PO - R.origin, PN) / Vector3.Dot(R.direction, PN); // plane vs. line intersection in algebric form. It find t as distance from the camera of the new point in the ray's direction.
Vector3 P = R.origin + R.direction * t; // Find the new point.
return P;
}
public void OnEndDrag(PointerEventData eventData)
{
// Do stuff when draggin ends. For example restore camera interaction.
if(GetComponent<Rigidbody>()!=null)
{
GetComponent<Rigidbody>().isKinematic = false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment