Question by
Chimaira · Nov 14, 2020 at 09:35 PM ·
scripting problemmeshmeshrenderermeshfilter
Why is my mesh not showing outside of an area?
So I am creating a game that uses a lantern function which I used a mesh to create. Everything is working as I want except once the player is moved outside of some area (seems to maybe be the original camera area) the mesh disappears.
https://youtu.be/qKB1XL3zXAE - Video of issue
using UnityEngine;
public class Lantern : MonoBehaviour
{
[SerializeField] public LayerMask layerMask;
[SerializeField] private Mesh mesh;
[SerializeField] private float fov;
[SerializeField] private Vector3 origin;
[SerializeField] private float startingAngle;
private void Start()
{
mesh = new Mesh();
GetComponent<MeshFilter>().mesh = mesh;
fov = 90f;
origin = Vector3.zero;
}
private void LateUpdate()
{
int rayCount = 25;
float angle = startingAngle;
float angleIncrease = fov / rayCount;
float viewDistance = 6f;
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, GameUtilities.GetVectorFromAngle(angle), viewDistance, layerMask);
if (raycastHit2D.collider == null)
{
//no hit
vertex = origin + GameUtilities.GetVectorFromAngle(angle) * viewDistance;
}
else
{
// hit object
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;
}
public void SetOrigin(Vector3 origin)
{
this.origin = origin;
}
public void SetAimDirection(Vector3 aimDirection)
{
startingAngle = GameUtilities.GetAngleFromVectorFloat(aimDirection) + fov / 2f;
}
}
Comment