Search Unity

Determining Plane's UV under the cursor

Discussion in 'Scripting' started by Vagrod, Jan 28, 2018.

  1. Vagrod

    Vagrod

    Joined:
    Aug 4, 2017
    Posts:
    82
    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:

    Code (CSharp):
    1.  
    2.  
    3. //....
    4. _collider = gameObject.GetComponent<Collider>(); // Plane's mesh collider
    5. //....
    6.  
    7.  
    8. void FixedUpdate()
    9.         {
    10.             RaycastHit hit;
    11.  
    12.             var p = UnityEngine.Input.mousePosition;
    13.  
    14.             if (_collider.Raycast(Camera.main.ScreenPointToRay(p), out hit, 100f))
    15.             {
    16.                 var meshCollider = hit.collider as MeshCollider;
    17.                 var rend = hit.collider.GetComponent<Renderer>();
    18.  
    19.                 if (rend == null || rend.sharedMaterial == null || rend.sharedMaterial.mainTexture == null || meshCollider == null)
    20.                     return;
    21.  
    22.                 var pixelUV = hit.textureCoord;
    23.  
    24.                 pixelUV.x *= rend.material.mainTexture.width;
    25.                 pixelUV.y *= rend.material.mainTexture.height;
    26.  
    27.                 Debug.Log("UV=[" + hit.textureCoord.x + ";" + hit.textureCoord.y + "]" + ", XY=[" + pixelUV.x + ";" + pixelUV.y + "]");
    28.             }
    29.         }
    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?
     

    Attached Files:

    • UVs.png
      UVs.png
      File size:
      1.6 MB
      Views:
      737
  2. Vagrod

    Vagrod

    Joined:
    Aug 4, 2017
    Posts:
    82
    UPD: I ended up ditching mouse pointer entirely. Code above actually works well if you hide cursor and just look at the collision detection. Now I am showing a really small sphere at the ray hit point, and when you move your mouse, this sphere smoothly follows plane surface: now this is my "pointer". It works really well, and even better than "real" pointer: my 3d-cursor actually follows object geometry. And as this sphere represent actual raycast hit point, precision is great.

    I really like this workaround, but question is still open.