using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.XR.Interaction.Toolkit; [RequireComponent(typeof(XRRayInteractor))] public class CrosshairDisplay : MonoBehaviour, IListener { [SerializeField] GameObject crosshairPrefab = null; [SerializeField] float maxDistance = 100f; XRRayInteractor ray; GameObject crosshair = null; Camera cam; new Renderer renderer; void Awake() { ray = GetComponent<XRRayInteractor>(); crosshair = Instantiate(crosshairPrefab); if (crosshair) renderer = crosshair.GetComponent<Renderer>(); cam = Camera.main; EventManager.Instance.AddListener(EVENT_TYPE.ON_FIRE_CROSSHAIR_ALPHA_CHANGED_LEFT, this); EventManager.Instance.AddListener(EVENT_TYPE.ON_FIRE_CROSSHAIR_ALPHA_CHANGED_RIGHT, this); } void Update() { if(crosshair && ray.TryGetCurrent3DRaycastHit(out RaycastHit hit)) { crosshair.transform.position = hit.point; Vector3 currentRotation = crosshair.transform.rotation.eulerAngles; Vector3 direction = hit.point - cam.transform.position; float eulerY = Quaternion.LookRotation(direction, Vector3.up).eulerAngles.y; crosshair.transform.rotation = Quaternion.Euler(currentRotation.x, eulerY, currentRotation.z); if (Vector3.Distance(hit.point, cam.transform.position) > maxDistance) renderer.enabled = false; else renderer.enabled = true; } } public void OnEvent<T>(EVENT_TYPE eventType, Component Sender, T param = default) { switch (eventType) { case EVENT_TYPE.ON_FIRE_CROSSHAIR_ALPHA_CHANGED_LEFT: renderer.material.SetFloat("_AlphaLeftEye", (dynamic)param); break; case EVENT_TYPE.ON_FIRE_CROSSHAIR_ALPHA_CHANGED_RIGHT: renderer.material.SetFloat("_AlphaRightEye", (dynamic)param); break; } } }