Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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

        }

    }
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away