- Home /
create mesh from equations dynamic
hi. i have some CAD mathematics equations that lead to draw close shape. how i can make a 3d mesh from it in unity ? it must be completely automatic system .any idea?
Answer by carrollh · Jan 14, 2015 at 07:09 PM
Your solution will be in two steps:
1) convert your equations to Vector3 coordinates. The example you show looks like it has two straight lines which would need a Vector3 at each end, but the curved ones would require you to split them up. Maybe you could solve for a x coordinate at 5 or 6 spots along the curve to get those points?
2) Add a GameObject to your scene with a MeshRenderer component and MeshFilter component added to it. Then dynamically create a mesh object with the coordinates you found in part one. This script should get you started:
using UnityEngine;
[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(MeshRenderer))]
public class DynamicSquare : MonoBehaviour {
private Vector3[] vertices;
private int[] triangles;
// private Vector2[] uvs; // if you want to add uv coordinates
void Start () {
/* The vertex indicies look like this, with these triangles
* 3 ------ 0
* | /|
* | / |
* | / |
* |/ |
* 2 ------ 1
*/
// the 4 vertices making up our square counterclock-wise from top right
vertices = new Vector3[4];
vertices[0] = new Vector3(1, 1, 0);
vertices[1] = new Vector3(1, 0, 0);
vertices[2] = new Vector3(0, 0, 0);
vertices[3] = new Vector3(0, 1, 0);
// list of index locations for the vertices making up each triangle
triangles = new int[6];
triangles[0] = 0;
triangles[1] = 1;
triangles[2] = 2;
triangles[3] = 0;
triangles[4] = 2;
triangles[5] = 3;
Mesh mesh = new Mesh();
mesh.vertices = vertices;
mesh.triangles = triangles;
//mesh.uvs = uvs; //<-- If you want to create uvs to map to a texture
mesh.name = "DynamicSquareMesh";
GetComponent<MeshFilter>().mesh = mesh;
}
}