Sinuousity

DraggableRigidbodyController.cs

Aug 29th, 2014
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.37 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4.  
  5. public class DraggableRigidbodyController : MonoBehaviour
  6. {
  7.     public List<string> draggableTags;
  8.     [Range(0.5f,0.99f)]
  9.     public float smoothness = 0.9f;
  10.     public float lift = 2f;
  11.     Rigidbody curObj = null;
  12.     public bool makeKinematic = true;
  13.     Plane movePlane;
  14.    
  15.     void TryClick ()
  16.     {
  17.         Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition);
  18.         RaycastHit hit;
  19.         if (Physics.Raycast(camRay,out hit))
  20.         {
  21.             if (hit.rigidbody == null)
  22.                 return;
  23.  
  24.             if (draggableTags.Contains(hit.rigidbody.tag))
  25.             {
  26.                 curObj = hit.rigidbody;
  27.                 if (makeKinematic)
  28.                     curObj.isKinematic = true;
  29.                 movePlane = new Plane(Vector3.up,curObj.transform.position);
  30.             }
  31.         }
  32.     }
  33.  
  34.     void FreeObject ()
  35.     {
  36.         if (makeKinematic)
  37.             curObj.isKinematic = false;
  38.  
  39.         curObj = null;
  40.     }
  41.  
  42.     void Update ()
  43.     {
  44.         if (Input.GetMouseButtonDown(0) && curObj == null)
  45.         {
  46.             TryClick();
  47.         }
  48.  
  49.         if (Input.GetMouseButtonUp(0) && curObj != null)
  50.         {
  51.             FreeObject ();
  52.         }
  53.  
  54.         if (curObj == null)
  55.             return;
  56.  
  57.         Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition);
  58.         float hitDist;
  59.         if (movePlane.Raycast(camRay,out hitDist))
  60.         {
  61.             Vector3 newPos = camRay.GetPoint(hitDist)+Vector3.up*lift;
  62.             curObj.MovePosition(Vector3.Lerp(curObj.transform.position, newPos,1f - smoothness));
  63.         }
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment