Debug용 법선을 Unity로 표시

5664 단어 Unity
Scene 뷰에만 표시
using UnityEngine;

[ExecuteInEditMode]
public class NormalHelper : MonoBehaviour {

    public float length = 1;

    public Vector3 bias;

    void Update() {


        var meshFilt = GetComponent<MeshFilter>();
        if (meshFilt == null) return;

        var mesh = meshFilt.mesh;

        Vector3[] vertices = mesh.vertices;
        Vector3[] normals = mesh.normals;

        for (var i = 0; i < normals.Length; i++)
        {
            Vector3 pos = vertices[i];
            pos.x *= transform.localScale.x;
            pos.y *= transform.localScale.y;
            pos.z *= transform.localScale.z;
            pos += transform.position + bias;

            Debug.DrawLine
            (
                pos,
                pos + normals[i] * length, Color.red);
        }
    }
}

Tangent 버전을 추가했습니다.

using UnityEngine;

[ExecuteInEditMode]
public class NormalHelper : MonoBehaviour {

    public float length = 1;

    public Vector3 bias;

    void Update() {


        var meshFilt = GetComponent<MeshFilter>();
        if (meshFilt == null) return;

        var mesh = meshFilt.mesh;

        Vector3[] vertices = mesh.vertices;
        Vector3[] normals = mesh.normals;
        Vector4[] tangent = mesh.tangents;

        for (var i = 0; i < normals.Length; i++)
        {

            Vector3 pos = vertices[i];
            pos.x *= transform.localScale.x;
            pos.y *= transform.localScale.y;
            pos.z *= transform.localScale.z;
            pos += transform.position + bias;

            //normal
            Debug.DrawLine
            (
                pos,
                pos + normals[i] * length, 
                Color.red
            );

            //ついでにtangentも可視化
            Debug.DrawLine
            (
                pos,
                pos + new Vector3( 
                        tangent[i].x,
                        tangent[i].y,
                        tangent[i].z
                    ) * length, 
                Color.blue
            );

        }

    }
}

좋은 웹페이지 즐겨찾기