【求助】根据mask图片生成网格,但是有一块黑色的,有大佬帮忙看
unity3d吧
全部回复
仅看楼主
level 9
子叶梧桐 楼主
上代码:
using UnityEngine;
public class MeshGeneratorScript : MonoBehaviour
{
// 用于生成网格的颜色纹理
public Texture2D colorTexture;
// 网格的单元格大小
public float gridSize = 0.1f;
private void Start()
{
// 在启动时生成网格
GenerateMesh();
}
private void GenerateMesh()
{
// 获取颜色纹理的宽度和高度
int width = colorTexture.width;
int height = colorTexture.height;
// 获取颜色纹理的像素数组
Color[] pixels = colorTexture.GetPixels();
// 计算顶点数量和三角形数量
int vertexCount = (width * height);
int triangleCount = (width - 1) * (height - 1)*6;
// 创建顶点数组、法线数组和UV坐标数组
Vector3[] vertices = new Vector3[vertexCount];
Vector3[] normals = new Vector3[vertexCount];
Vector2[] uv = new Vector2[vertexCount];
// 创建三角形索引数组
int[] triangles = new int[triangleCount];
int vertexIndex = 0;
int triangleIndex = 0;
Color previousColor = pixels[0];
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
// 获取当前像素的颜色
Color pixelColor = pixels[y * width + x];
if (pixelColor != previousColor)
{
// 根据像素位置生成顶点
vertices[vertexIndex] = new Vector3(x * gridSize, 0, y * gridSize);
Debug.Log("当前像素位置:" + new Vector3(x * gridSize, 0, y * gridSize));
// 设置法线方向为向上
normals[vertexIndex] = Vector3.up;
// 设置UV坐标
uv[vertexIndex] = new Vector2((float)x / width, (float)y / height);
if (x < width - 1 && y < height - 1)
{
// 生成三角形索引
triangles[triangleIndex] = vertexIndex;
triangles[triangleIndex + 1] = vertexIndex + width;
triangles[triangleIndex + 2] = vertexIndex + width + 1;
triangles[triangleIndex + 3] = vertexIndex;
triangles[triangleIndex + 4] = vertexIndex + width + 1;
triangles[triangleIndex + 5] = vertexIndex + 1;
triangleIndex += 6;
}
vertexIndex++;
}
previousColor = pixelColor;
}
}
// 创建网格并赋值给MeshFilter组件
Mesh mesh = new Mesh();
mesh.vertices = vertices;
mesh.normals = normals;
mesh.uv = uv;
mesh.triangles = triangles;
GetComponent<MeshFilter>().mesh = mesh;
}
}
2023年07月07日 10点07分 1
level 9
子叶梧桐 楼主
有没有大佬帮忙看看怎么哪里出问题了[乖]
2023年07月07日 10点07分 2
1