Advertisement
Guest User

SphericalRaycaster.cs

a guest
Apr 7th, 2015
742
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.64 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class SphericalRaycaster : MonoBehaviour {
  5.  
  6.     public int motorCount = 6;
  7.     public float motorRayDistance = 5f;
  8.     public float rayHeightFromBase = 0.1f;
  9.     public LayerMask rayLayers;
  10.    
  11.     Transform bTransform;
  12.     float[] motorDistances;
  13.    
  14.     /*
  15.         The motorDistances array contains each motors distance from a wall
  16.         in it's direction. Index 0 is straight forward from the player, increasing
  17.         the index gets the next motor/ray in clockwise direction. A value of
  18.         'float.MaxValue' means it did not hit a wall (Maybe use -1 instead).
  19.    
  20.     */
  21.    
  22.     void Awake()
  23.     {
  24.         this.bTransform = GetComponent<Transform>();
  25.         this.motorDistances = new float[this.motorCount];
  26.     }
  27.    
  28.     void GetMotorDistances()
  29.     {
  30.         if(this.motorDistances.Length != this.motorCount)
  31.         {
  32.             this.motorDistances = new float[this.motorCount];
  33.         }
  34.         RaycastHit hit;
  35.         for(int i=0; i<this.motorCount; i++)
  36.         {
  37.             float progress = ((float)i) / this.motorCount;
  38.             float angle = progress * Mathf.PI * 2;
  39.             Vector3 origin = this.bTransform.position + (Vector3.up * this.rayHeightFromBase);
  40.             Vector3 direction = this.bTransform.rotation * new Vector3(Mathf.Sin(angle), 0f, Mathf.Cos(angle));
  41.             Ray ray = new Ray(origin, direction);
  42.             Color debugCol = Color.red;
  43.             if(Physics.Raycast(ray, out hit, this.motorRayDistance, this.rayLayers))
  44.             {
  45.                 this.motorDistances[i] = hit.distance;
  46.                 debugCol = Color.green;
  47.             }
  48.             else
  49.             {
  50.                 this.motorDistances[i] = float.MaxValue;
  51.             }
  52.             Debug.DrawRay(ray.origin, ray.direction * this.motorRayDistance, debugCol);
  53.         }
  54.     }
  55.    
  56.     void Update ()
  57.     {
  58.         this.GetMotorDistances();
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement