Hi!
I have a plane object. This plane is fixed relative to camera (plane is camera’s child and always facing the camera – image attached). This plane has some RenderTexture on it. Now I want to know, what UV coordinate is currently under the mouse cursor.
The following script is sitting on this plane object:
//....
_collider = gameObject.GetComponent<Collider>(); // Plane's mesh collider
//....
void FixedUpdate()
{
RaycastHit hit;
var p = UnityEngine.Input.mousePosition;
if (_collider.Raycast(Camera.main.ScreenPointToRay(p), out hit, 100f))
{
var meshCollider = hit.collider as MeshCollider;
var rend = hit.collider.GetComponent<Renderer>();
if (rend == null || rend.sharedMaterial == null || rend.sharedMaterial.mainTexture == null || meshCollider == null)
return;
var pixelUV = hit.textureCoord;
pixelUV.x *= rend.material.mainTexture.width;
pixelUV.y *= rend.material.mainTexture.height;
Debug.Log("UV=[" + hit.textureCoord.x + ";" + hit.textureCoord.y + "]" + ", XY=[" + pixelUV.x + ";" + pixelUV.y + "]");
}
}
But coordinates I see in the log are very strange. First of all, when I change aspect ratio in a viewport, point that had XY[51,466] in 16:10 becomes XY[95,464] in 4:3 and so on. Secondly, offset is so huge that I am getting UV readings even if mouse pointer is nowhere near this plane.
How to correctly get these UV readings regardless of screen size?