public static EdgeInfo FindEdge(Transform transform, ViewCastInfo minViewCast, ViewCastInfo maxViewCast, float viewRadius, int edgeResolveIterations, float edgeDstThreshold, LayerMask obstacleMask) { var minAngle = minViewCast.angle; var maxAngle = maxViewCast.angle; var minPoint = Vector3.zero; var maxPoint = Vector3.zero; for (var i = 0; i < edgeResolveIterations; i++) { var angle = (minAngle + maxAngle) / 2; var newViewCast = ViewCastInfo.GetViewCast(transform, angle, viewRadius, obstacleMask); var edgeDstThresholdExceeded = Mathf.Abs(minViewCast.distance - newViewCast.distance) > edgeDstThreshold; if (newViewCast.hit == minViewCast.hit && !edgeDstThresholdExceeded) { minAngle = angle; minPoint = newViewCast.point; } else { maxAngle = angle; maxPoint = newViewCast.point; } } return(new EdgeInfo(minPoint, maxPoint)); }
void DrawFieldOfView() { var stepCount = Mathf.RoundToInt(viewAngle * meshResolution); var stepAngleSize = viewAngle / stepCount; var viewPoints = new List <Vector3> (); var oldViewCast = new ViewCastInfo(); for (var i = 0; i <= stepCount; i++) { var angle = transform.eulerAngles.y - viewAngle / 2 + stepAngleSize * i; var newViewCast = ViewCastInfo.GetViewCast(transform, angle, viewRadius, obstacleMask); if (i > 0) { var edgeDstThresholdExceeded = Mathf.Abs(oldViewCast.distance - newViewCast.distance) > edgeDstThreshold; if (oldViewCast.hit != newViewCast.hit || (oldViewCast.hit && newViewCast.hit && edgeDstThresholdExceeded)) { var edge = EdgeInfo.FindEdge(transform, oldViewCast, newViewCast, viewRadius, edgeResolveIterations, edgeDstThreshold, obstacleMask); if (edge.pointA != Vector3.zero) { viewPoints.Add(edge.pointA); } if (edge.pointB != Vector3.zero) { viewPoints.Add(edge.pointB); } } } viewPoints.Add(newViewCast.point); oldViewCast = newViewCast; } var vertexCount = viewPoints.Count + 1; var vertices = new Vector3[vertexCount]; var triangles = new int[(vertexCount - 2) * 3]; vertices[0] = Vector3.zero; for (var i = 0; i < vertexCount - 1; i++) { vertices[i + 1] = transform.InverseTransformPoint(viewPoints[i]) + Vector3.forward * maskCutawayDst; 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(); }