Hi there,
I’m creating a mesh in code, currently just a triangle, which represents my characters’ field of view, to capture what enemy units are in view when they take aim. The mesh is generated in code (the details of which I know little about but seem to have gotten working out of cobbled-together samples), and that seems to be working fine. You can see the nice green triangle it’s making in this screenshot:
However, the mesh collider I’m then creating and applying to this object always takes the shape of a box bigger than the triangle mesh it’s supposed to be taking its shape from. The way I’m applying the mesh to the collider looks to me pretty much the same as all the code-created mesh collider examples I’ve found, but I haven’t yet come across anyone else complaining of this particular problem. I have no idea where it’s getting this box shape from, but it’s clearly drawing from the mesh in some way, since it always seems to scale to be just this much larger than the triangle. I’d greatly appreciate any help figuring out what’s going on - thanks! The relevant code:
GameObject CreateAimMesh(float aimArc, float range)
{
GameObject plane = new GameObject("AimingMesh");
//////MESH
MeshFilter meshFilter = plane.AddComponent<MeshFilter>();
Mesh m = new Mesh();
m.name = "aiming mesh";
m.vertices = new Vector3[] {
new Vector3(0, 0.1f, 0),
new Vector3(-(Mathf.Tan(aimArc/2) * range), 0.1f, range),
new Vector3((Mathf.Tan(aimArc/2) * range), 0.1f, range),
};
//note: this bit is pure copy-paste guesswork; hopefully isn't relevant though?
m.uv = new Vector2[] {
new Vector2 (0, 0),
new Vector2 (0, 1),
new Vector2(1, 0),
};
m.triangles = new int[] { 0, 1, 2 };
m.RecalculateNormals();
m.RecalculateBounds();
meshFilter.mesh = m;
//////DEBUG VISUAL (untouched from the sample I copied from)
MeshRenderer renderer = plane.AddComponent<MeshRenderer>();
renderer.material.shader = Shader.Find ("Particles/Additive");
Texture2D tex = new Texture2D(1, 1);
tex.SetPixel(0, 0, Color.green);
tex.Apply();
renderer.material.mainTexture = tex;
renderer.material.color = Color.green;
//////COLLISION DETECTION
MeshCollider coll = plane.AddComponent<MeshCollider>();
coll.sharedMesh = m;
coll.convex = true;
coll.isTrigger = true;
AimMesh aimScript = plane.AddComponent<AimMesh>(); //script that keeps track of targets inside the mesh on entry/exit
plane.transform.position = bulletSpawn.transform.position;
plane.transform.parent = bulletSpawn.transform;
plane.transform.localEulerAngles = new Vector3(0, 90, 0);
aimScript.InitAimScript(this);
return plane;
}