LoginSignup
13
7

More than 3 years have passed since last update.

UnityでDebug用に法線を表示する

Last updated at Posted at 2017-03-22

Sceneビューのみに表示されます

image

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
            );

        }

    }
}
13
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
7