XRoom_Unity/Assets/BNG Framework/Scripts/Extras/LaserPointer.cs
2025-05-31 10:20:20 +03:30

65 lines
2.2 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR;
namespace BNG {
/// <summary>
/// A simple laser pointer that draws a line with a dot at the end
/// </summary>
public class LaserPointer : MonoBehaviour {
public float MaxRange = 25f;
public LayerMask ValidLayers;
public Transform LaserEnd;
public bool Active = true;
public BNG.Grabbable grabbable;
LineRenderer line;
// Start is called before the first frame update
void Start() {
rightController = InputDevices.GetDeviceAtXRNode(XRNode.RightHand);
line = GetComponent<LineRenderer>();
}
private UnityEngine.XR.InputDevice rightController;
void LateUpdate() {
if(Active) {
line.enabled = (grabbable.BeingHeld) &&
((rightController.TryGetFeatureValue(UnityEngine.XR.CommonUsages.trigger, out float isPressed) && isPressed > 0.5f)||Input.GetKey(KeyCode.Z));
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, out hit, MaxRange, ValidLayers, QueryTriggerInteraction.Ignore)) {
line.useWorldSpace = true;
line.SetPosition(0, transform.position);
line.SetPosition(1, hit.point);
// Add dot at line's end
LaserEnd.gameObject.SetActive(true);
LaserEnd.position = hit.point;
LaserEnd.rotation = Quaternion.FromToRotation(Vector3.forward, hit.normal);
}
else {
line.useWorldSpace = true;
line.SetPosition(0, transform.position);
line.SetPosition(1, transform.position + transform.forward * MaxRange); // جهت لیزر حفظ می‌شود
LaserEnd.gameObject.SetActive(false);
}
}
else {
LaserEnd.gameObject.SetActive(false);
if (line) {
line.enabled = false;
}
}
}
}
}