UP-Viagg-io/Viagg-io/Assets/Scripts/ClickOnRenderTexture.cs
2025-04-08 16:57:01 +02:00

54 lines
2.2 KiB
C#

using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.EventSystems;
using UnityEngine.XR.Interaction.Toolkit;
using System.Collections.Generic;
public class ClickOnRenderTexture : MonoBehaviour
{
public Camera secondaryCamera; // The camera rendering the UI to the RenderTexture
public RenderTexture renderTexture; // The RenderTexture applied to the mesh
public MeshCollider meshCollider; // The mesh collider of the object showing the RenderTexture
public XRRayInteractor xrRayInteractor; // The XR Ray Interactor component attached to the controller
private void Update()
{
// Ensure XRRayInteractor is assigned
if (xrRayInteractor == null)
{
Debug.LogWarning("XRRayInteractor not assigned!");
return;
}
// Check if the XRRayInteractor is selecting an object
if (xrRayInteractor.hasSelection)
{
Ray ray = new Ray(xrRayInteractor.transform.position, xrRayInteractor.transform.forward);
// Raycast into the mesh displaying the RenderTexture
if (Physics.Raycast(ray, out RaycastHit hit))
{
if (hit.collider == meshCollider) // If the ray hits the mesh with the RenderTexture
{
// Get the UV coordinates of the hit point
Vector2 uv = hit.textureCoord;
Vector2 screenPoint = new Vector2(uv.x * renderTexture.width, uv.y * renderTexture.height);
// Simulate a UI click on the RenderTexture (mapped to the secondary camera's UI)
PointerEventData eventData = new PointerEventData(EventSystem.current);
eventData.position = screenPoint;
List<RaycastResult> results = new List<RaycastResult>();
EventSystem.current.RaycastAll(eventData, results);
// Execute the click event on the UI element under the ray
foreach (var result in results)
{
ExecuteEvents.Execute(result.gameObject, eventData, ExecuteEvents.pointerClickHandler);
}
}
}
}
}
}