- Home /
Question by
jeppe79 · Feb 03, 2020 at 09:20 AM ·
uicanvasraycastingrendertextureportal
UI interaction via RenderTexture
Hello,
I have a scene set up like this:
Main Camera(With PhysicsRaycast component attached to be able to raycast on the Quad)
Quad with RenderTexture
UICamera
Canvas (Worldspace with UICamera targeted) + (GraphicsRaycaster and one button attached)
My code below lets me extract the texture position of the RenderTexture hit, but I am stuck on how to convert this to a GraphicRaycast to project the ray on the same position on the actual UI to click the button.
Any help with this would be much appreciated! -Jesper
{ using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
}
public class RaycastRenderTexture : MonoBehaviour
{
public Camera mainCamera;
public Camera uiCamera;
// used to determine how many texture hitpoints the gameObject has
public RenderTexture renderTexture;
// used to determine distance between renderTextureObject and canvas
public Canvas canvas;
public GameObject renderTextureObject;
// Start is called before the first frame update
void Start()
{
// Calculate distance from Canvas to RenderTexture Object (quad) to adjust raycast X value
float distanceFromCanvasToRT = renderTextureObject.transform.position.x - canvas.transform.position.x;
Debug.Log(distanceFromCanvasToRT);
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
Debug.Log("RAY: " + ray);
if (Physics.Raycast(ray, out hit))
{
// Get hit at texture pixel position of RenderTexture on Quad
float texturePositionX = hit.textureCoord.x * renderTexture.width;
float texturePositionY = hit.textureCoord.y * renderTexture.height;
Vector2 pixelHit = new Vector2(Mathf.Floor(texturePositionX), Mathf.Floor(texturePositionY));
Debug.Log("TEXTURE HIT: " + pixelHit);
// Get world coordinates
Debug.Log("TRANSFORM_POS: " + hit.collider.gameObject.transform.position);
// Get local coordinates of object's position inside parent
Debug.Log("TRANSFORM_LOCALPOS: " + hit.collider.gameObject.transform.localPosition);
}
}
}
}
Comment