Skip to content

Instantly share code, notes, and snippets.

@gutoplusgamedev
Created December 23, 2015 20:25
Show Gist options
  • Select an option

  • Save gutoplusgamedev/d29b63bfa74395c335b9 to your computer and use it in GitHub Desktop.

Select an option

Save gutoplusgamedev/d29b63bfa74395c335b9 to your computer and use it in GitHub Desktop.
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;
}
}
Copy link

ghost commented Dec 24, 2018

What's the license for this? GPL3?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment