c# - 如何从表示为浮点数组的高度图创建 3D 网格
问题描述
我试图了解如何从存储为一维浮点数组的高度图构造 3D 网格。我之前看到的唯一示例使用了 2D 浮点数组,我正在努力解决这里涉及的数学问题。任何对此的见解将不胜感激。为了您的方便,我已经评论了我还不太了解的代码。
代码来源:https ://github.com/SebLague/Hydraulic-Erosion
public void ContructMesh () {
Vector3[] verts = new Vector3[mapSize * mapSize];
int[] triangles = new int[(mapSize - 1) * (mapSize - 1) * 6];
int t = 0;
//Note that default mapSize is 255
for (int i = 0; i < mapSize * mapSize; i++) {
//Following code is not properly understood
int x = i % mapSize;
int y = i / mapSize;
int meshMapIndex = y * mapSize + x;
Vector2 percent = new Vector2 (x / (mapSize - 1f), y / (mapSize - 1f));
Vector3 pos = new Vector3 (percent.x * 2 - 1, 0, percent.y * 2 - 1) * scale;
pos += Vector3.up * map[meshMapIndex] * elevationScale; //Elevation scale is 20 by default
verts[meshMapIndex] = pos;
//End of misunderstood code
if (x != mapSize - 1 && y != mapSize - 1) {
t = (y * (mapSize - 1) + x) * 3 * 2;
triangles[t + 0] = meshMapIndex + mapSize;
triangles[t + 1] = meshMapIndex + mapSize + 1;
triangles[t + 2] = meshMapIndex;
triangles[t + 3] = meshMapIndex + mapSize + 1;
triangles[t + 4] = meshMapIndex + 1;
triangles[t + 5] = meshMapIndex;
t += 6;
}
}
Mesh mesh = new Mesh();
mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;
mesh.vertices = verts;
mesh.triangles = triangles;
mesh.RecalculateNormals ();
解决方案
具体有什么不明白的?
int x = i % mapSize; // Get the x location of the current point
int y = i / mapSize; // Get the y location of the current point
// This should be equal to i, IDK why this is even calculated
int meshMapIndex = y * mapSize + x;
// How far along either direction are we?
Vector2 percent = new Vector2 (x / (mapSize - 1f), y / (mapSize - 1f));
// Make a new vector that scales the X and Y coordinates up.
// The Y coordinate is set to the Z element in this vector
// Presumably because whatever you use to render uses the Y element as "up"
// And the X-Z plane is the horizontal plane
// Also normalize X and Z to lie between -1*scale and 1*scale
Vector3 pos = new Vector3 (percent.x * 2 - 1, 0, percent.y * 2 - 1) * scale;
// Add the value at the current index, times the scale, as the Y element of pos
pos += Vector3.up * map[meshMapIndex] * elevationScale; //Elevation scale is 20 by default
// The X-Z values of pos give you the location of the vertex in the horizontal plane
// The Y value of pos gives you the height
// save the newly calculated pos in verts
verts[meshMapIndex] = pos;
推荐阅读
- java - 离子构建项目失败:无法确定任务':app:lintVitalRelease'的依赖关系
- python - 遍历索引目录的服务器 URL 并读取文件
- perl - perl cpan 安装与 GIT Perl cpan 安装冲突我该如何纠正?
- dotnetzip - 为什么我的 zip 文件夹没有用密码锁定,但里面的文件被锁定了?
- c# - 将 http 请求添加到 .NET 中的多部分/混合请求
- ios - 从 ViewController 追加流?
- c - 为什么使用 -O(1/2/3) 选项进行优化会干扰 scanf()?
- javascript - 如何在 javascript 中到达嵌套对象内部?
- bash - 在特定符号之间过滤具有匹配 ID 字符串的多 fasta 文件
- algorithm - 确定是否可以将一组节点视为有向无环图的孤立子图