public MapChunk(float[,] heightMap, int size, Vector2 offset, float scale) { this.offset = new Vector2(offset.x * scale, offset.y * scale); this.scale = scale; mesh = new MapChunkMesh[size + 1, size + 1]; for (int x = 0; x < size + 1; x++) { for (int y = 0; y < size + 1; y++) { mesh[x, y] = new MapChunkMesh { vertex = new Vector3((x + offset.x) * scale, heightMap[x + 1, y + 1], (y + offset.y) * scale) }; } } for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { Vector3 sideAC = mesh[x + 1, y].vertex - mesh[x, y].vertex; Vector3 sideAB = mesh[x, y + 1].vertex - mesh[x, y].vertex; Vector3 sideAD = mesh[x + 1, y + 1].vertex - mesh[x, y].vertex; mesh[x, y].normalLeft = Vector3.Cross(sideAB, sideAD).normalized; mesh[x, y].normalRight = Vector3.Cross(sideAD, sideAC).normalized; } } }
static public float GetHeight(float x, float y) { if (x > sideLength || y > sideLength || x < 0 || y < 0) { return(0); } //https://www.scratchapixel.com/lessons/3d-basic-rendering/ray-tracing-rendering-a-triangle/ray-triangle-intersection-geometric-solution MapChunkMesh mesh = GetChunk(x, y).GetMesh(x, y); Vector3 vertex = mesh.vertex; Vector3 normal = mesh.GetNormal(x, y); return((normal.x * (x - vertex.x) + normal.z * (y - vertex.z)) / -normal.y + vertex.y); }