Created
December 23, 2015 20:25
-
-
Save gutoplusgamedev/d29b63bfa74395c335b9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections.Generic; | |
public class LineOfSight : MonoBehaviour | |
{ | |
public float apertureAngle; | |
public float maxSightDistance; | |
public int iterations; | |
private GameObject _lineOfSightGo; | |
void Start () | |
{ | |
_lineOfSightGo = new GameObject ("LineOfSight"); | |
_lineOfSightGo.AddComponent<MeshFilter>(); | |
_lineOfSightGo.AddComponent<MeshRenderer>(); | |
_lineOfSightGo.GetComponent<MeshRenderer>().sharedMaterial = new Material (Shader.Find ("Standard")); | |
} | |
void Update () | |
{ | |
_lineOfSightGo.GetComponent<MeshFilter>().mesh = GenerateSightMesh (iterations); | |
} | |
Mesh GenerateSightMesh (int iterations) | |
{ | |
Mesh m = new Mesh (); | |
List<Vector3> vertices = new List<Vector3>(); | |
List<int> triangles = new List<int>(); | |
Vector3 startingPoint = transform.position; | |
vertices.Add (startingPoint); | |
float angleStep = apertureAngle / iterations; | |
RaycastHit hit; | |
for (int i = 0; i <= iterations; i++) | |
{ | |
float angle = (-apertureAngle * 0.5f) + (i * angleStep); | |
Vector3 sightVector = Quaternion.AngleAxis (angle, transform.up) * transform.forward; | |
if (Physics.Raycast (startingPoint, sightVector, out hit, maxSightDistance)) | |
{ | |
vertices.Add (startingPoint + sightVector * hit.distance); | |
} | |
else | |
{ | |
vertices.Add (startingPoint + sightVector * maxSightDistance); | |
} | |
if (i >= 1) | |
{ | |
triangles.Add (0); | |
triangles.Add (i); | |
triangles.Add (i + 1); | |
} | |
} | |
m.vertices = vertices.ToArray(); | |
m.triangles = triangles.ToArray(); | |
return m; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What's the license for this? GPL3?