MouseSplit.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Shatter Toolkit
  2. // Copyright 2015 Gustav Olsson
  3. using UnityEngine;
  4. namespace ShatterToolkit.Helpers
  5. {
  6. public class MouseSplit : MonoBehaviour
  7. {
  8. public int raycastCount = 5;
  9. protected bool started = false;
  10. protected Vector3 start, end;
  11. public void Update()
  12. {
  13. if (Input.GetMouseButtonDown(0))
  14. {
  15. start = Input.mousePosition;
  16. started = true;
  17. }
  18. if (Input.GetMouseButtonUp(0) && started)
  19. {
  20. end = Input.mousePosition;
  21. // Calculate the world-space line
  22. Camera mainCamera = Camera.main;
  23. float near = mainCamera.nearClipPlane;
  24. Vector3 line = mainCamera.ScreenToWorldPoint(new Vector3(end.x, end.y, near)) - mainCamera.ScreenToWorldPoint(new Vector3(start.x, start.y, near));
  25. // Find game objects to split by raycasting at points along the line
  26. for (int i = 0; i < raycastCount; i++)
  27. {
  28. Ray ray = mainCamera.ScreenPointToRay(Vector3.Lerp(start, end, (float)i / raycastCount));
  29. RaycastHit hit;
  30. if (Physics.Raycast(ray, out hit))
  31. {
  32. Plane splitPlane = new Plane(Vector3.Normalize(Vector3.Cross(line, ray.direction)), hit.point);
  33. hit.collider.SendMessage("Split", new Plane[] { splitPlane }, SendMessageOptions.DontRequireReceiver);
  34. break;
  35. }
  36. }
  37. started = false;
  38. }
  39. }
  40. }
  41. }