Tools.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. // Shatter Toolkit
  2. // Copyright 2015 Gustav Olsson
  3. using UnityEngine;
  4. namespace ShatterToolkit
  5. {
  6. public static class Tools
  7. {
  8. public static bool IsPointInsideTriangle(ref Vector3 point, ref Vector3 triangle0, ref Vector3 triangle1, ref Vector3 triangle2)
  9. {
  10. Vector3 normal = Vector3.Cross(triangle1 - triangle0, triangle2 - triangle0);
  11. return IsPointInsideTriangle(ref point, ref triangle0, ref triangle1, ref triangle2, ref normal);
  12. }
  13. public static bool IsPointInsideTriangle(ref Vector3 point, ref Vector3 triangle0, ref Vector3 triangle1, ref Vector3 triangle2, ref Vector3 triangleNormal)
  14. {
  15. // Discard zero-size triangles; slower but more logical than considering the triangle edges as outside
  16. if (Vector3.Cross(triangle1 - triangle0, triangle2 - triangle0) == Vector3.zero)
  17. {
  18. return false;
  19. }
  20. Vector3 pointTo0 = triangle0 - point;
  21. Vector3 pointTo1 = triangle1 - point;
  22. Vector3 pointTo2 = triangle2 - point;
  23. if (Vector3.Dot(Vector3.Cross(pointTo0, pointTo1), triangleNormal) < 0.0f ||
  24. Vector3.Dot(Vector3.Cross(pointTo1, pointTo2), triangleNormal) < 0.0f ||
  25. Vector3.Dot(Vector3.Cross(pointTo2, pointTo0), triangleNormal) < 0.0f)
  26. {
  27. return false;
  28. }
  29. return true;
  30. }
  31. }
  32. }