CrossHair.cs 2.7 KB

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