Skip to content

Instantly share code, notes, and snippets.

@marcelschmidtdev
Created March 30, 2016 00:41
Show Gist options
  • Save marcelschmidtdev/434320b0f50e0cad66f6d82fa2ec5f63 to your computer and use it in GitHub Desktop.
Save marcelschmidtdev/434320b0f50e0cad66f6d82fa2ec5f63 to your computer and use it in GitHub Desktop.
Renders normals of a geometry mesh in Unity
using UnityEngine;
using System.Collections;
public class NormalRenderer : MonoBehaviour
{
public float Threshold = 360.0f;
public float Offset = 0;
void OnDrawGizmos()
{
Vector3[] normals = GetComponent<MeshFilter>().sharedMesh.normals;
Vector3[] vertices = GetComponent<MeshFilter>().sharedMesh.vertices;
int[] triangles = GetComponent<MeshFilter>().sharedMesh.triangles; //contains vertex indices for vertices building a triangle
for(int i = 0;i<triangles.Length; i+=3)
{
//only use normals of first vertex ->flatten shading (else we have to use an average value of all 3 normals of the triangle)
int v1 = triangles[i];
int v2 = triangles[i+1];
int v3 = triangles[i+2];
// Vector3 p = vertices[v1];
// p = this.transform.TransformPoint(p);
Vector3 n = this.transform.TransformDirection(normals[v1]);
Vector3 middle = (vertices[v1] + vertices[v2] + vertices[v3]) / 3;
middle = this.transform.TransformPoint(middle);
if(Vector3.Angle(Vector3.down, n) <= Threshold)
{
Gizmos.DrawLine(middle + n.normalized * Offset, middle + n);
}
// Gizmos.DrawLine(p, p + n);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment