Unity Texture2D如何转换为法线贴图
时间: 2024-05-13 22:20:10 浏览: 126
可以使用NormalMapFromTexture函数将Texture2D转换为法线贴图。以下是示例代码:
```
public Texture2D normalTexture;
public void CreateNormalMap()
{
Texture2D tempTex = new Texture2D(normalTexture.width, normalTexture.height, TextureFormat.RGB24, true);
Graphics.CopyTexture(normalTexture, tempTex);
Texture2D normalMap = NormalMapFromTexture(tempTex);
}
private Texture2D NormalMapFromTexture(Texture2D sourceTexture)
{
Texture2D normalMap = new Texture2D(sourceTexture.width, sourceTexture.height, TextureFormat.ARGB32, true);
Color[] textureColors = sourceTexture.GetPixels();
Color[] normalColors = new Color[textureColors.Length];
float bumpiness = 0.75f; // 调整法线贴图的凹凸程度
float textureWidth = (float)sourceTexture.width;
float textureHeight = (float)sourceTexture.height;
int pix = 0;
for (int y = 0; y < sourceTexture.height; y++)
{
for (int x = 0; x < sourceTexture.width; x++)
{
float xLeft = textureColors[pix - 1].grayscale * bumpiness;
float xRight = textureColors[pix + 1].grayscale * bumpiness;
float yUp = textureColors[pix - sourceTexture.width].grayscale * bumpiness;
float yDown = textureColors[pix + sourceTexture.width].grayscale * bumpiness;
float xDelta = ((xLeft - xRight) + 1) * 0.5f;
float yDelta = ((yUp - yDown) + 1) * 0.5f;
normalColors[pix] = new Color(xDelta, yDelta, 1.0f, 1.0f);
pix++;
}
}
normalMap.SetPixels(normalColors);
normalMap.Apply();
return normalMap;
}
```
阅读全文