Utils.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using UnityEngine;
  6. public static class Utils
  7. {
  8. static Texture2D _whiteTexture;
  9. public static Texture2D WhiteTexture
  10. {
  11. get
  12. {
  13. if( _whiteTexture == null )
  14. {
  15. _whiteTexture = new Texture2D( 1, 1 );
  16. _whiteTexture.SetPixel( 0, 0, Color.white );
  17. _whiteTexture.Apply();
  18. }
  19. return _whiteTexture;
  20. }
  21. }
  22. public static Rect GetScreenRect( Vector3 screenPosition1, Vector3 screenPosition2 )
  23. {
  24. // Move origin from bottom left to top left
  25. screenPosition1.y = Screen.height - screenPosition1.y;
  26. screenPosition2.y = Screen.height - screenPosition2.y;
  27. // Calculate corners
  28. var topLeft = Vector3.Min( screenPosition1, screenPosition2 );
  29. var bottomRight = Vector3.Max( screenPosition1, screenPosition2 );
  30. // Create Rect
  31. return Rect.MinMaxRect( topLeft.x, topLeft.y, bottomRight.x, bottomRight.y );
  32. }
  33. public static Bounds GetViewportBounds( Camera camera, Vector3 screenPosition1, Vector3 screenPosition2 )
  34. {
  35. var v1 = camera.ScreenToViewportPoint( screenPosition1 );
  36. var v2 = camera.ScreenToViewportPoint( screenPosition2 );
  37. var min = Vector3.Min( v1, v2 );
  38. var max = Vector3.Max( v1, v2 );
  39. min.z = camera.nearClipPlane;
  40. max.z = camera.farClipPlane;
  41. //min.z = 0.0f;
  42. //max.z = 1.0f;
  43. var bounds = new Bounds();
  44. bounds.SetMinMax( min, max );
  45. return bounds;
  46. }
  47. public static void DrawScreenRect( Rect rect, Color color )
  48. {
  49. GUI.color = color;
  50. GUI.DrawTexture( rect, WhiteTexture );
  51. GUI.color = Color.white;
  52. }
  53. public static void DrawScreenRectBorder( Rect rect, float thickness, Color color )
  54. {
  55. // Top
  56. Utils.DrawScreenRect( new Rect( rect.xMin, rect.yMin, rect.width, thickness ), color );
  57. // Left
  58. Utils.DrawScreenRect( new Rect( rect.xMin, rect.yMin, thickness, rect.height ), color );
  59. // Right
  60. Utils.DrawScreenRect( new Rect( rect.xMax - thickness, rect.yMin, thickness, rect.height ), color );
  61. // Bottom
  62. Utils.DrawScreenRect( new Rect( rect.xMin, rect.yMax - thickness, rect.width, thickness ), color );
  63. }
  64. }