I'm trying to make my player have a cone of vision which is made of several rays that form a polygon, the player can only see what is under the polygon. Right now the vision stops when it hits a wall, but I want the player to be able to see what the wall looks like, so the vision should end once it exits the walls collider. The vision is a layer mask and everything is hidden under a big black square attached to the camera. This is the code for the vision cone, which I got from a youtube tutorial.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using CodeMonkey.Utils;
public class FOV : MonoBehaviour
{
[SerializeField] private PlayerMovement player;
[SerializeField] private LayerMask layerMask;
private Vector3 origin;
[SerializeField] private float fov;
private Mesh mesh;
private float startingAngle;
[SerializeField] float viewDistance;
void Start()
{
mesh = new Mesh();
GetComponent<MeshFilter>().mesh = mesh;
}
void Update()
{
int rayCount = 80;
float angle = startingAngle;
float angleIncrease = fov / rayCount;
Vector3[] vertices = new Vector3[rayCount + 1 + 1];
Vector2[] uv = new Vector2[vertices.Length];
int[] triangles = new int[rayCount * 3];
vertices[0] = origin;
int vertexIndex = 1;
int triangleIndex = 0;
for (int i = 0; i <= rayCount; i++)
{
Vector3 vertex;
RaycastHit2D raycastHit2D = Physics2D.Raycast(origin, UtilsClass.GetVectorFromAngle(angle), viewDistance, layerMask);
if(raycastHit2D.collider == null)
{
vertex = origin + UtilsClass.GetVectorFromAngle(angle) * viewDistance;
}
else
{
vertex = raycastHit2D.point;
}
vertices[vertexIndex] = vertex;
if (i > 0)
{
triangles[triangleIndex + 0] = 0;
triangles[triangleIndex + 1] = vertexIndex - 1;
triangles[triangleIndex + 2] = vertexIndex;
triangleIndex += 3;
}
vertexIndex++;
angle -= angleIncrease;
}
mesh.vertices = vertices;
mesh.uv = uv;
mesh.triangles = triangles;
mesh.RecalculateBounds();
}
public void SetOrigin(Vector3 origin)
{
this.origin = origin;
}
public void SetAimDirection(Vector3 aimDirection)
{
startingAngle = UtilsClass.GetAngleFromVectorFloat(aimDirection) + fov / 2f;
}
}
I tried to use an answer from someone with the same issue, but the answer was for 3D unity and was trying to achieve something different than me so it didn't help. I also tried to make the polygon do a little bit further than where the ray hit, but then the player was able to see through corners and thin walls which looks weird.