UICursor.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System;
  2. using UnityEngine;
  3. [RequireComponent(typeof(UISprite))]
  4. [AddComponentMenu("NGUI/Examples/UI Cursor")]
  5. public class UICursor : MonoBehaviour
  6. {
  7. private void Awake()
  8. {
  9. UICursor.instance = this;
  10. }
  11. private void OnDestroy()
  12. {
  13. UICursor.instance = null;
  14. }
  15. private void Start()
  16. {
  17. this.mTrans = base.transform;
  18. this.mSprite = base.GetComponentInChildren<UISprite>();
  19. if (this.uiCamera == null)
  20. {
  21. this.uiCamera = NGUITools.FindCameraForLayer(base.gameObject.layer);
  22. }
  23. if (this.mSprite != null)
  24. {
  25. this.mAtlas = this.mSprite.atlas;
  26. this.mSpriteName = this.mSprite.spriteName;
  27. if (this.mSprite.depth < 100)
  28. {
  29. this.mSprite.depth = 100;
  30. }
  31. }
  32. }
  33. private void Update()
  34. {
  35. Vector3 mousePosition = Input.mousePosition;
  36. if (this.uiCamera != null)
  37. {
  38. mousePosition.x = Mathf.Clamp01(mousePosition.x / (float)Screen.width);
  39. mousePosition.y = Mathf.Clamp01(mousePosition.y / (float)Screen.height);
  40. this.mTrans.position = this.uiCamera.ViewportToWorldPoint(mousePosition);
  41. if (this.uiCamera.orthographic)
  42. {
  43. Vector3 localPosition = this.mTrans.localPosition;
  44. localPosition.x = Mathf.Round(localPosition.x);
  45. localPosition.y = Mathf.Round(localPosition.y);
  46. this.mTrans.localPosition = localPosition;
  47. }
  48. }
  49. else
  50. {
  51. mousePosition.x -= (float)Screen.width * 0.5f;
  52. mousePosition.y -= (float)Screen.height * 0.5f;
  53. mousePosition.x = Mathf.Round(mousePosition.x);
  54. mousePosition.y = Mathf.Round(mousePosition.y);
  55. this.mTrans.localPosition = mousePosition;
  56. }
  57. }
  58. public static void Clear()
  59. {
  60. if (UICursor.instance != null && UICursor.instance.mSprite != null)
  61. {
  62. UICursor.Set(UICursor.instance.mAtlas, UICursor.instance.mSpriteName);
  63. }
  64. }
  65. public static void Set(UIAtlas atlas, string sprite)
  66. {
  67. if (UICursor.instance != null && UICursor.instance.mSprite)
  68. {
  69. UICursor.instance.mSprite.atlas = atlas;
  70. UICursor.instance.mSprite.spriteName = sprite;
  71. UICursor.instance.mSprite.MakePixelPerfect();
  72. UICursor.instance.Update();
  73. }
  74. }
  75. public static UICursor instance;
  76. public Camera uiCamera;
  77. private Transform mTrans;
  78. private UISprite mSprite;
  79. private UIAtlas mAtlas;
  80. private string mSpriteName;
  81. }