Question by
DADDADDAD · Mar 09 at 09:05 AM ·
raycastmeshraycasthit2d
Raycast seems to stop working as the y cor of the player (origin of the raycast) changes by more than a certain amount
It is attatched to a raycast object that has the player object as a serialized field and a layermask with the wall and ground layers. The layers are set properly for all the objects.
for some reason the ray cast just stops working as the player goes up or down by more than some amount
link to video of it happening https://youtu.be/Evzr-Fdk2TQ
the purpose is to use this raycast/mesh to only render the area the player is currently in
this is my raycast code. (the 370 fov and raycount is to stop flickering, the problem persists even with those numbers set lower)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FieldOfView : MonoBehaviour
{
[SerializeField] PlayerMove player;
[SerializeField] LayerMask layermask;
private Mesh mesh;
private void Start()
{
mesh = new Mesh();
GetComponent<MeshFilter>().mesh = mesh;
}
private void Update()
{
float fov = 370f;
Vector3 origin = player.transform.position;
int raycount = 370;
float angle = 0f;
float angleIncrease = fov / raycount;
float viewDistance = 20f;
Vector3[] verts = new Vector3[raycount +2];//setting up verts
Vector2[] uv = new Vector2[verts.Length];//setting up uv
int[] tris = new int[raycount*3];//setting up tris
verts[0] = origin;
int vertIndex = 1;
int triIndex = 0;
//cycle through all rays
for (int i=0; i<=raycount; i++)
{
Vector3 vertex;
//vertex = origin + GetVectorFromAngle(angle) * viewDistance;
RaycastHit2D raycasthit2D = Physics2D.Raycast(origin, GetVectorFromAngle(angle), viewDistance, layermask);
if (raycasthit2D.collider == null)
{
//did NOT hit object
vertex = origin + GetVectorFromAngle(angle) * viewDistance;//locate rays
}
else
{
//did hit object
vertex = raycasthit2D.point;
}
verts[vertIndex] = vertex;
//generate tris
if (i>0)
{
tris[triIndex+0] = 0;
tris[triIndex + 1] = vertIndex - 1;
tris[triIndex + 2] = vertIndex;
triIndex += 3;
}
vertIndex++;
//move to next angle
angle -= angleIncrease;
}
//upload all values to mesh
mesh.vertices = verts;
mesh.uv = uv;
mesh.triangles = tris;
}
public Vector3 GetVectorFromAngle(float angle)
{
float angleRad = angle * (Mathf.PI / 180f);//0.01745f = (Mathf.PI / 180f)
return new Vector3(Mathf.Cos(angleRad), Mathf.Sin(angleRad));
}
}
Comment