Skip to content

Instantly share code, notes, and snippets.

@rstecca
Last active September 29, 2021 11:32
Show Gist options
  • Select an option

  • Save rstecca/6e583504e1e0ba7f2192d64d3036daae to your computer and use it in GitHub Desktop.

Select an option

Save rstecca/6e583504e1e0ba7f2192d64d3036daae to your computer and use it in GitHub Desktop.

Revisions

  1. rstecca revised this gist Mar 5, 2019. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion MakeA3DObjectDraggable.cs
    Original file line number Diff line number Diff line change
    @@ -21,7 +21,7 @@ public class MakeA3DObjectDraggable : MonoBehaviour, IDragHandler, IBeginDragHan

    void Start () {
    if (Camera.main.GetComponent<PhysicsRaycaster>() == null)
    Debug.Log("Camera doesn't ahve a physics raycaster.");
    Debug.LogError("Camera doesn't have a physics raycaster.");

    m_cam = Camera.main;
    }
  2. rstecca created this gist May 8, 2018.
    49 changes: 49 additions & 0 deletions MakeA3DObjectDraggable.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    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;

    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)
    {
    Ray R = m_cam.ScreenPointToRay(Input.mousePosition); // Get the ray from mouse position
    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.

    transform.position = P;
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
    // Do stuff when dragging begins. For example suspend camera interaction.
    }

    public void OnEndDrag(PointerEventData eventData)
    {
    // Do stuff when draggin ends. For example restore camera interaction.
    }
    }