unity C#代码实现normalMap

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class CreateMormalMap : MonoBehaviour {

    public Texture2D tex0;

    public Texture2D tex1;

    // Use this for initialization

    void Start () {

        if (tex0 == null || tex1 == null) return;

for(int h = 1; h < tex0.height-1; h++)

        {

            for(int w = 1; w < tex0.width-1; w++)

            {

                //得到横向左右的差值

                Color  left = tex0.GetPixel(w - 1, h);

                Color right = tex0.GetPixel(w + 1, h);

                Color u = right - left;

                //得到横向上下的差值

                Color top = tex0.GetPixel(w, h - 1);

                Color bottom = tex0.GetPixel(w, h + 1);

                Color v = bottom-top ;


                //色转灰度算法

                float u_b = ((int)(u.r * 19595 + u.g * 38469 + u.b * 7472) >> 16);

                float v_b = ((int)(v.r * 19595 + v.g * 38469 + v.b * 7472) >> 16);

                //叉乘得到法向量

                Vector3 normal = Vector3.Cross(new Vector3(1, 0, u_b), new Vector3(0, 1, v_b)).normalized;


                float r = normal.x * 0.5f + 0.5f;

                float g = normal.y * 0.5f + 0.5f;

                float b = normal.z * 0.5f + 0.5f;

                tex1.SetPixel(w, h, new Color(r, g, b));

            }

        }

        tex1.Apply(false);

    }

// Update is called once per frame

}

注意:所需要转化的图片要勾选

无止境!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容