MatchingScalePicker.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace UnityARInterface
  5. {
  6. public class MatchingScalePicker : ARBase
  7. {
  8. [SerializeField]
  9. private Transform m_LevelGeometry;
  10. private Bounds GetRenderBounds(GameObject go)
  11. {
  12. var totalBounds = new Bounds();
  13. totalBounds.SetMinMax(Vector3.one * Mathf.Infinity, -Vector3.one * Mathf.Infinity);
  14. foreach (var renderer in go.GetComponentsInChildren<Renderer>())
  15. {
  16. var bounds = renderer.bounds;
  17. var totalMin = totalBounds.min;
  18. totalMin.x = Mathf.Min(totalMin.x, bounds.min.x);
  19. totalMin.y = Mathf.Min(totalMin.y, bounds.min.y);
  20. totalMin.z = Mathf.Min(totalMin.z, bounds.min.z);
  21. var totalMax = totalBounds.max;
  22. totalMax.x = Mathf.Max(totalMax.x, bounds.max.x);
  23. totalMax.y = Mathf.Max(totalMax.y, bounds.max.y);
  24. totalMax.z = Mathf.Max(totalMax.z, bounds.max.z);
  25. totalBounds.SetMinMax(totalMin, totalMax);
  26. }
  27. return totalBounds;
  28. }
  29. private void Update()
  30. {
  31. if (Input.GetMouseButton(0))
  32. {
  33. var camera = GetCamera();
  34. Ray ray = camera.ScreenPointToRay(Input.mousePosition);
  35. var planeLayer = GetComponent<ARPlaneVisualizer>().planeLayer;
  36. int layerMask = 1 << planeLayer;
  37. RaycastHit rayHit;
  38. if (Physics.Raycast(ray, out rayHit, float.MaxValue, layerMask))
  39. {
  40. var arController = GetFirstEnabledControllerInChildren();
  41. var bounds = GetRenderBounds(m_LevelGeometry.gameObject);
  42. var maxLevelDimension = Mathf.Max(bounds.size.x, bounds.size.z);
  43. var planeTransform = rayHit.collider.transform.parent;
  44. var planeScale = planeTransform.localScale;
  45. var planeExtents = new Vector2(planeScale.x, planeScale.z);
  46. var minPlaneDimension = Mathf.Min(planeExtents.x, planeExtents.y);
  47. arController.pointOfInterest = bounds.center;
  48. arController.scale = maxLevelDimension / minPlaneDimension;
  49. arController.rotation = planeTransform.localRotation;
  50. arController.AlignWithPointOfInterest(planeTransform.position);
  51. }
  52. }
  53. }
  54. }
  55. }