我试图将地图集上的纹理应用到网格上,通过该网格上的UV阵列来重复,但我有点迷失在坐标转换上。
例如,如果所需的纹理在材质地图集上的x,y像素,我如何转换和获取这些坐标并应用于网格?我正在用块加载器动态地绘制网格,用于一个体素游戏,我把它放在正方形体素上,但是现在当添加更复杂的网格时,需要知道如何将纹理应用于这些网格。
我想代码应该是类似的,但我希望有人能帮我填空:
void UpdateMesh()
{
UVList.Clear();
Mesh mesh = this.GetComponent<MeshFilter>().mesh;
for (int i = 0; i < mesh.uv.Length; i++)
{
UVList.Add(GetUVTextureFromAtlas(mesh.uv[i].x, mesh.uv[i].y, voxelType);
}
mesh.uv = UVList.ToArray();
}
//converts UV position expected from mesh model to position on texture atlas
Vector2 GetUVTextureFromAtlas(float x, float y, int voxelType)
{
Vector2 uv;
Vector2 textureAtlasPos = GetTextureOffset(voxelType); // returns texture pos from atlas
//not exactly sure what this would look like for code to convert
//from the position on the atlas to the expected UV position based on
//expected UV position (i.e. from 1,0 to whereever the texture is on the atlas)
return uv;
}
发布于 2015-10-28 08:43:07
基本UV存在于单位矩形上:
(0, 1) (1, 1)
+-----------------+
| |
| |
| |
| |
| |
| |
+-----------------+
(0, 0) (1, 0)
你想把这个空间映射到地图集上的一个不同的矩形上:
(xmin, ymax) (xmax, ymax)
+-----------------+
| |
| |
| |
| |
| |
| |
+-----------------+
(xmin, ymin) (xmax, ymin)
由于您的基本UV范围从0
到1
,所以使用Lerp
非常简单:
float xout = Mathf.Lerp(xmin, xmax, x);
float yout = Mathf.Lerp(ymin, ymax, y);
您需要xmin
、ymin
、xmax
和ymax
的适当值,这意味着您需要知道地图集上纹理的位置和大小。
我还假设这四个值在UV空间。如果您的地图集坐标指定为像素坐标,则可以使用InverseLerp
将这些坐标转换为UV坐标。假设您在(x, y)
有一个(xlen, ylen)
大小的纹理,在一个(xsize, ysize)
大小的地图集上有一个纹理:
xmin = Mathf.InverseLerp(0, xsize, x);
xmax = Mathf.InverseLerp(0, xsize, x + xlen);
ymin = Mathf.InverseLerp(0, ysize, y);
ymax = Mathf.InverseLerp(0, ysize, y + ylen);
如果你对数学很满意的话,改进这种方法是完全可能的,但这是它的基本依据。
https://gamedev.stackexchange.com/questions/110448
复制相似问题