zrrz111

SphereCastTest

May 19th, 2016
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.84 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class SphereCastTest : MonoBehaviour {
  5.    
  6.     public float radiusOfSphere, distance;
  7.     Rigidbody selectedRigidbody;
  8.     public GameObject rayOrigin;
  9.  
  10.     public LayerMask layerMask;
  11.  
  12.     void Update () {
  13.         Vector3 origin = rayOrigin.transform.position;
  14.         Vector3 direction = rayOrigin.transform.forward;
  15.  
  16.         if(Input.GetButtonDown("Fire1")) {            
  17.             RaycastHit hit;
  18.             if (Physics.SphereCast(origin, radiusOfSphere, direction, out hit, distance, layerMask))
  19.             {
  20.                 if (hit.collider.gameObject.tag == "Pickable")
  21.                 {
  22.                     selectedRigidbody = hit.rigidbody;
  23.                     selectedRigidbody.constraints =
  24.                         RigidbodyConstraints.FreezePositionZ
  25.                         | RigidbodyConstraints.FreezeRotationX
  26.                         | RigidbodyConstraints.FreezeRotationY
  27.                         | RigidbodyConstraints.FreezeRotationZ;
  28.                 }
  29.             }
  30.         }
  31.  
  32.         if (Input.GetButtonUp("Fire1"))
  33.         {
  34.             if (selectedRigidbody != null)
  35.             {
  36.                 selectedRigidbody.constraints = RigidbodyConstraints.None;
  37.                 selectedRigidbody = null;
  38.             }
  39.         }
  40.     }
  41.  
  42.     void OnDrawGizmos() {
  43.         Vector3 origin = rayOrigin.transform.position;
  44.         Vector3 direction = rayOrigin.transform.forward;
  45.  
  46.         Color color1 = new Color(1f, 1f, 1f, 0.5f);
  47.         Color color2 = new Color(0f, 0f, 0f, 0.5f);
  48.         for (float t = 0, step = 0.05f; t < 1f; t += step)
  49.         {
  50.             Gizmos.color = Color.Lerp(color1, color2, t);
  51.             Vector3 pos = Vector3.Lerp(origin, origin + (direction*distance), t);
  52.             Gizmos.DrawSphere(pos, radiusOfSphere);
  53.         }
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment