Skip to content

Instantly share code, notes, and snippets.

@naokirin
Last active May 23, 2016 02:33
Show Gist options
  • Save naokirin/44618ce28674927c7d8541ce03d6c3fb to your computer and use it in GitHub Desktop.
Save naokirin/44618ce28674927c7d8541ce03d6c3fb to your computer and use it in GitHub Desktop.
UnityのSceneビューでメッシュの法線を表示する
using UnityEngine;
using System.Linq;
public static class GizmosArrowDrawer
{
public static void Draw(Vector3 pos, Vector3 direction, float arrowHeadLength = 0.25f, float arrowHeadAngle = 20.0f)
{
Gizmos.DrawRay(pos, direction);
Vector3 right = Quaternion.LookRotation(direction) * Quaternion.Euler(0, 180 + arrowHeadAngle, 0) * new Vector3(0, 0, 1);
Vector3 left = Quaternion.LookRotation(direction) * Quaternion.Euler(0, 180 - arrowHeadAngle, 0) * new Vector3(0, 0, 1);
Gizmos.DrawRay(pos + direction, right * arrowHeadLength);
Gizmos.DrawRay(pos + direction, left * arrowHeadLength);
}
public static void ForGizmo(Vector3 pos, Vector3 direction, Color color, float arrowHeadLength = 0.25f, float arrowHeadAngle = 20.0f)
{
Gizmos.color = color;
Draw(pos, direction, arrowHeadLength, arrowHeadAngle);
}
}
public class GizmosMeshNormalDrawer : MonoBehaviour
{
[SerializeField]
private Mesh mesh;
[SerializeField, Range(0, 10000)]
private int disableCount = 500;
[SerializeField]
private float arrowLength = 0.5f;
void OnDrawGizmosSelected()
{
if (mesh == null)
{
return;
}
var vertexCount = mesh.vertices.Length;
if (vertexCount > disableCount)
{
Debug.LogFormat("Disable normals because meshes has {0} vertices.", vertexCount);
return;
}
for (int m = 0; m < mesh.subMeshCount; ++m)
{
for (int i = 0; i < mesh.vertices.Length; i += 1)
{
var pos = mesh.vertices[i];
pos = Vector3.Scale(pos, transform.lossyScale);
pos = transform.rotation * pos;
pos += transform.position;
var normal = mesh.normals[i];
if (Vector3.zero != normal)
{
GizmosArrowDrawer.ForGizmo(pos, normal.normalized * arrowLength, Color.cyan, arrowLength / 5);
}
}
var triangles = mesh.GetTriangles(m);
for (int i = 0; i < triangles.Length; i += 3)
{
var v1 = mesh.vertices[triangles[i]];
var v2 = mesh.vertices[triangles[i+1]];
var v3 = mesh.vertices[triangles[i+2]];
var vec1 = v2 - v1;
var vec2 = v3 - v1;
var pos = (v1 + v2 + v3) / 3;
pos = Vector3.Scale(pos, transform.lossyScale);
pos = transform.rotation * pos;
pos += transform.position;
var normal = Vector3.Cross(vec1, vec2);
if (Vector3.zero != normal)
{
GizmosArrowDrawer.ForGizmo(pos, normal.normalized * arrowLength, Color.green, arrowLength / 5);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment