using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; /* 准心对象 */ public class CrossHair : MonoBehaviour { public static CrossHair ins; private Image image = null; private bool open = false; private bool visiable = false; void Awake() { ins = this; } void OnDestroy() { if (ins == this) ins = null; } void Start() { this.image = this.GetComponent(); this.open = UserSettings.ins.openCrossHair; this.visiable = this.image.enabled; this.SetVisiable(false); //如果是靶子场景,把准心改为黑色 if (SceneManager.GetActiveScene().name.Equals("Game")) { this.image.color = Color.black; } } void Update() { if (open) SetVisiable(ArmBow.ins && ArmBow.ins.IsCanShoot()); } void SetVisiable(bool value) { if (this.visiable == value) return; this.visiable = value; this.GetComponent().enabled = this.visiable; } public void SetOpen(bool open) { this.open = open; if (!this.open) { SetVisiable(false); } } public bool GetOpen() { return this.open; } public RaycastHit GetRaycastHit() { float maxDistance = 100; int layerMask = 1 << 8; //TargetLayerMask RaycastHit raycastHit; Ray ray; if (Camera.main.name.EndsWith("Fixed")) { ray = new Ray(BowCamera.ins.transform.position, BowCamera.ins.transform.forward); } else { ray = Camera.main.ScreenPointToRay(this.transform.position, Camera.MonoOrStereoscopicEye.Mono); } Physics.Raycast(ray.origin, ray.direction, out raycastHit, maxDistance, layerMask); return raycastHit; } #region 固定相机更新 RectTransform _parentRTF; RectTransform parentRTF { get { if (!_parentRTF) { _parentRTF = transform.parent.GetComponent(); } return _parentRTF; } } Vector3 centerPoint = new Vector3(0.5f, 0.5f, 0); Vector3 targetPosition; public void UpdatePostionWhenFixedCamera() { if (!visiable) return; Transform transform = BowCamera.ins.transform; Ray ray = new Ray(transform.position, transform.forward); RaycastHit hitInfo; if (Physics.Raycast(ray, out hitInfo, 100)) { targetPosition = hitInfo.point; } else { targetPosition = transform.position + transform.forward * 100f; } Vector3 v3 = Camera.main.WorldToViewportPoint(targetPosition) - centerPoint; v3.x *= parentRTF.rect.width; v3.y *= parentRTF.rect.height; v3.z = 0; this.transform.localPosition = v3; } #endregion }