I am trying to create a mesh in code that has a cone shape to it. It adjusts it’s shape based on raycasts. I intend to use it as a sort of security camera detection cone.
I think the only problem I have left is that I can’t figure out what the triangle points are supposed to be? I can’t seem to get that to work dynamically based on the size.
Some other questions though, will this be too resource intensive? Is there a better way to do this kind of dynamic mesh shaping?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class test3 : MonoBehaviour
{
public int size = 5;
public float fwdMultiplier = 2;
public float maxRayDist = 10;
public LayerMask mask;
Mesh mesh;
public List<Vector3> verticies = new List<Vector3>();
public List<int> triangles = new List<int>();
private void Start()
{
mesh = new Mesh();
GetComponent<MeshFilter>().mesh = mesh;
}
public void Update()
{
CreateShape();
UpdateMesh();
}
private void CreateShape()
{
verticies.Clear();
triangles.Clear();
verticies.Add(new Vector3(0, 0, 0)); //the tip of the cone aka the gameobject current position
for (int x = -size; x <= size; x++)
{
for (int y = -size; y <= size; y++)
{
RaycastHit hit;
Ray ray = new Ray(transform.position, transform.forward * fwdMultiplier + transform.TransformDirection(x, y, 0));
if (Physics.Raycast(ray, out hit, maxRayDist, mask))
{
Debug.DrawLine(transform.position, hit.point, Color.red);
if (x == -size || x == size || y == -size || y == size)
{
verticies.Add(transform.InverseTransformPoint(hit.point));
}
}
else
{
Debug.DrawRay(transform.position, transform.forward * fwdMultiplier + transform.TransformDirection(x, y, 0), Color.green);
if (x == -size || x == size || y == -size || y == size)
{
verticies.Add(transform.InverseTransformPoint(transform.position + ray.direction * maxRayDist));
}
}
}
}
//The problem area. Not sure how to handle dynamically setting the triangles up.
for (int i = 1; i < verticies.Count - 1; i++)
{
triangles.Add(0);
triangles.Add(i);
triangles.Add(i + 1);
}
}
void UpdateMesh()
{
mesh.Clear();
mesh.vertices = verticies.ToArray();
mesh.triangles = triangles.ToArray();
mesh.RecalculateNormals();
}
}
Answer
Add a comment
While looking for a solution to my problem I encountered this video. At 8:30 it seems similar to what I’m trying to do.