CrossHair.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using UnityEngine.SceneManagement;
  6. /* 准心对象 */
  7. public class CrossHair : MonoBehaviour
  8. {
  9. public static CrossHair ins;
  10. private Image image = null;
  11. private bool open = false;
  12. private bool visiable = false;
  13. void Awake()
  14. {
  15. ins = this;
  16. }
  17. void Start()
  18. {
  19. this.image = this.GetComponent<Image>();
  20. this.open = UserSettings.ins.openCrossHair;
  21. this.visiable = this.image.enabled;
  22. this.SetVisiable(false);
  23. //如果是靶子场景,把准心改为黑色
  24. if (SceneManager.GetActiveScene().name.Equals("Game")) {
  25. this.image.color = Color.black;
  26. }
  27. }
  28. void Update()
  29. {
  30. if (open) SetVisiable(ArmBow.ins && ArmBow.ins.IsCanShoot());
  31. }
  32. void SetVisiable(bool value)
  33. {
  34. if (this.visiable == value) return;
  35. this.visiable = value;
  36. this.GetComponent<Image>().enabled = this.visiable;
  37. }
  38. public void SetOpen(bool open) {
  39. this.open = open;
  40. if (!this.open) {
  41. SetVisiable(false);
  42. }
  43. }
  44. public bool GetOpen() {
  45. return this.open;
  46. }
  47. public RaycastHit GetRaycastHit() {
  48. float maxDistance = 100;
  49. int layerMask = 1 << 8; //TargetLayerMask
  50. RaycastHit raycastHit;
  51. Ray ray;
  52. if (Camera.main.name.EndsWith("Fixed")) {
  53. ray = new Ray(BowCamera.ins.transform.position, BowCamera.ins.transform.forward);
  54. } else {
  55. ray = Camera.main.ScreenPointToRay(this.transform.position, Camera.MonoOrStereoscopicEye.Mono);
  56. }
  57. Physics.Raycast(ray.origin, ray.direction, out raycastHit, maxDistance, layerMask);
  58. return raycastHit;
  59. }
  60. #region 固定相机更新
  61. RectTransform _parentRTF;
  62. RectTransform parentRTF {
  63. get {
  64. if (!_parentRTF) {
  65. _parentRTF = transform.parent.GetComponent<RectTransform>();
  66. }
  67. return _parentRTF;
  68. }
  69. }
  70. Vector3 centerPoint = new Vector3(0.5f, 0.5f, 0);
  71. Vector3 targetPosition;
  72. public void UpdatePostionWhenFixedCamera() {
  73. if (!visiable) return;
  74. Transform transform = BowCamera.ins.transform;
  75. Ray ray = new Ray(transform.position, transform.forward);
  76. RaycastHit hitInfo;
  77. if (Physics.Raycast(ray, out hitInfo, 100)) {
  78. targetPosition = hitInfo.point;
  79. } else {
  80. targetPosition = transform.position + transform.forward * 100f;
  81. }
  82. Vector3 v3 = Camera.main.WorldToViewportPoint(targetPosition) - centerPoint;
  83. v3.x *= parentRTF.rect.width;
  84. v3.y *= parentRTF.rect.height;
  85. v3.z = 0;
  86. this.transform.localPosition = v3;
  87. }
  88. #endregion
  89. }