我尝试编写一些代码来可视化自上而下的射击游戏的视野。 我向角色周围发出了射线,并收集了该射线是否命中的信息。 我将这些点存储在列表中,并尝试划分三角形。 我的问题就从那里开始。如果光线没有碰到障碍,那就没有问题。它可以创建网格。但是,如果光线撞到障碍物,它就无法形成三角形。它只会在我的角色周围产生奇怪的事物。
有我的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class fieldOfView : MonoBehaviour {
public float viewDistance;
public LayerMask obstacleMask;
public float viewAngle;
public float meshResolution;
public MeshFilter viewMeshFilter;
public Mesh viewMesh;
private void Start()
{
viewMesh = new Mesh();
viewMesh.name = "View Mesh";
viewMeshFilter.mesh = viewMesh;
}
private void Update()
{
DrawFieldOfView();
}
Vector3 DirFromAngle(float angle)
{
angle *= Mathf.Deg2Rad;
return new Vector3(Mathf.Sin(angle), 0, Mathf.Cos(angle));
}
void DrawFieldOfView()
{
int stepCount = Mathf.RoundToInt(viewAngle / meshResolution);
List<Vector3> viewPoints = new List<Vector3>();
List<Vector3> hitPoints = new List<Vector3>();
RaycastHit hit;
for(int i = 0; i <= stepCount; i++)
{
float angle = transform.eulerAngles.y +i * meshResolution;
if(Physics.Raycast(transform.position,DirFromAngle(angle),out hit, obstacleMask))
{
viewPoints.Add(hit.point);
Debug.DrawLine(transform.position, hit.point);
hitPoints.Add(hit.point);
}
else
{
viewPoints.Add(transform.position + DirFromAngle(angle) * viewDistance);
Debug.DrawLine(transform.position, transform.position + DirFromAngle(angle) * viewDistance);
}
}
int vertexCount = viewPoints.Count + 1;
Vector3[] vertices = new Vector3[vertexCount];
int[] triangles = new int[(vertexCount - 2) * 3];
vertices[0] = Vector3.zero;
for(int i = 0; i < vertexCount-1; i++)
{
vertices[i + 1] = viewPoints[i];
if (i < vertexCount - 2)
{
triangles[i * 3] = 0;
triangles[i * 3 + 1] = i + 1;
triangles[i * 3 + 2] = i + 2;
}
}
viewMesh.Clear();
viewMesh.vertices = vertices;
viewMesh.triangles = triangles;
viewMesh.RecalculateNormals();
}
}