项目中有需求动态生成法线贴图,研究了下从高度图生成法线贴图的方法,代码放在文末,可依据具体情况进行修改,理论上也可以通过其他数据源转换到法线贴图。
我的例子是取的灰度值作为了高度值。
参考连接
private void HeightMapToNormalMap(Texture2D texArg)
{
int width = texArg.width;
int height = texArg.height;
Texture2D texture2D = new Texture2D(width, height);
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
Color sColor = new Color(1, 0, texArg.GetPixel(i + 1, j).grayscale - texArg.GetPixel(i - 1, j).grayscale);
Color tColor = new Color(0, 1, texArg.GetPixel(i, j + 1).grayscale - texArg.GetPixel(i, j - 1).grayscale);
Vector3 sv = new Vector3(sColor.r, sColor.g, sColor.b);
Vector3 tv = new Vector3(tColor.r, tColor.g, tColor.b);
Vector3 cross = (Vector3.Cross(sv, tv).normalized * 0.5f) + (Vector3.one * 0.5f);
texture2D.SetPixel(i, j, new Color(cross.x, cross.y, cross.z));
}
}
texture2D.Apply();
byte[] bytes = texture2D.EncodeToPNG();
File.WriteAllBytes(@"C:\Users\Desktop\MyNormalMap.png", bytes);
}