Last active
August 28, 2024 06:43
-
-
Save maxkcy/d8407c1f2c1cb3a8b46af43e8372861e to your computer and use it in GitHub Desktop.
Mesh Generation for 3D Graphing calculator in Unity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 8-27-24 | |
// This is the code for my youtube video https://youtu.be/Orfc-HsCI_s. It is only for generating the front mesh of the 6 sides. | |
// I hope you will be able to figure out how to make the rest of the sides. | |
// (The reason I have not put the rest of the code below is because I am not following DRY, and don't want to refactor the code rn.) | |
// I don't believe this is a good method for generating the mesh, but I was just unable to think of a better way. | |
// This is just something simple that returns a passing result. If you know how to, or have any idea, please share with me. | |
// I'd like of know different ways to create a 3D mesh. | |
// Furthermore, to solve a 3D equation, in here, because it is for testing, I've provided a hard coded equation. | |
public int resolution = 100; | |
public float size = 5f; | |
private void GenerateMeshFront() | |
{ | |
Mesh mesh = new Mesh(); | |
GetComponent<MeshFilter>().mesh = mesh; | |
Vector3[] vertices = new Vector3[(resolution) * (resolution)]; | |
int[] triangles = new int[(resolution - 1) * (resolution - 1) * 6]; | |
float step = size / resolution; | |
int triangleIndex = 0; | |
for (int i = 0; i < resolution; i++) | |
{ | |
for (int j = 0; j < resolution; j++) | |
{ | |
float y = -size / 2 + i * step; | |
float x = -size / 2 + j * step; | |
float z = CalculateZFront(x, y); | |
if (z != 0) | |
{ | |
vertices[i * (resolution) + j] = new Vector3(x, y, z); | |
} | |
if (i < resolution - 1 && j < resolution - 1) | |
{ | |
int btmLeft = i * (resolution) + j; | |
int btmRight = btmLeft + 1; | |
int topLeft = (i + 1) * (resolution) + j; | |
int topRight = topLeft + 1; | |
triangles[triangleIndex++] = btmLeft; | |
triangles[triangleIndex++] = topLeft; | |
triangles[triangleIndex++] = topRight; | |
triangles[triangleIndex++] = topRight; | |
triangles[triangleIndex++] = btmRight; | |
triangles[triangleIndex++] = btmLeft; | |
} | |
} | |
} | |
mesh.vertices = vertices; | |
mesh.triangles = triangles; | |
mesh.RecalculateNormals(); | |
float CalculateZFront(float x, float y) | |
{ | |
// Sphere equation | |
//float zSquared = 1 - x * x - y * y; | |
// Hyperboloid equation | |
float zSquared = x * x - y * y; | |
return -Mathf.Sqrt(Mathf.Max(0, zSquared)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment