PolygonBlocker.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using UnityEngine;
  2. using System.Collections;
  3. [AddComponentMenu("Cocuy/PolygonBlocker")]
  4. [RequireComponent(typeof(PolygonCollider2D))]
  5. public class PolygonBlocker : MonoBehaviour {
  6. public FluidSimulator m_fluid;
  7. bool m_bInitialised = false;
  8. private PolygonCollider2D m_collider;
  9. void Start()
  10. {
  11. m_collider = GetComponent<PolygonCollider2D>();
  12. }
  13. void BlockFluid(bool bStatic)
  14. {
  15. if (m_collider && m_fluid)
  16. {
  17. Vector2[] points = m_collider.points;
  18. int size = points.Length;
  19. if (size >= 3)
  20. {
  21. Ray ray1 = new Ray(transform.TransformPoint(points[0]), new Vector3(0, 0, 1));
  22. RaycastHit h1 = new RaycastHit();
  23. if (m_fluid.GetComponent<Collider>().Raycast(ray1, out h1, 10))
  24. {
  25. Ray ray2 = new Ray(transform.TransformPoint(points[1]), new Vector3(0, 0, 1));
  26. RaycastHit h2 = new RaycastHit();
  27. if (m_fluid.GetComponent<Collider>().Raycast(ray2, out h2, 10))
  28. {
  29. for (int i = 2; i < size; ++i)
  30. {
  31. Ray ray3 = new Ray(transform.TransformPoint(points[i]), new Vector3(0, 0, 1));
  32. RaycastHit h3 = new RaycastHit();
  33. if (m_fluid.GetComponent<Collider>().Raycast(ray3, out h3, 10))
  34. {
  35. m_fluid.AddObstacleTriangle(h1.textureCoord, h2.textureCoord, h3.textureCoord, bStatic);
  36. }
  37. h2 = h3;
  38. }
  39. }
  40. }
  41. }
  42. }
  43. }
  44. void LateUpdate()
  45. {
  46. if (!m_bInitialised)
  47. {
  48. if (gameObject.isStatic)
  49. {
  50. BlockFluid(true);
  51. }
  52. m_bInitialised = true;
  53. }
  54. if (!gameObject.isStatic)
  55. {
  56. BlockFluid(false);
  57. }
  58. }
  59. }