Unity图片(高度图)转法线贴图

项目中有需求动态生成法线贴图,研究了下从高度图生成法线贴图的方法,代码放在文末,可依据具体情况进行修改,理论上也可以通过其他数据源转换到法线贴图。
我的例子是取的灰度值作为了高度值。
参考连接

    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);
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值