texture coord from rayhit on mesh

Hello, I have some code that is almost working. When i click on this mesh quad i have setup it uses setpixel32 to put a red box on the clicked point (it uses setpixel32 on a child sprite texture2d). I use raycasthit providing the coordinates from screenpointtoray(Input.mousePosition). It works perfectly if i click on the exact middle. However, the further away i am from the middle the further the box is from where i click. Please see code below:

RaycastHit hit;
Vector2 PixelUV;
if (!Physics.Raycast(CamToScreen.ScreenPointToRay(Input.mousePosition), out hit))
return;
PixelUV = hit.textureCoord;
PixelUV.x *= 128;
PixelUV.y *= 128;

// I then send the PixelUV.x - 5 and PixelUV.y-5 with a 10x10 square to the setpixel32 function

The parent object is a mesh with scale set to 1.28. Has a mesh collider and the script to catch the click. There is a child object that has the sprite and the texture. The texture is 128x128. Any clue as to what I’m doing wrong?

This looks ok to me, if you want to post an example project I can have a look.

The only other thing I would do before using the UV is to clamp it to 0…1

e.g.

PixelUV = hit.textureCoord;
PixelUV.x = PixelUV.x % 1.0f;
PixelUV.y = PixelUV.y % 1.0f;

UV coordinates are from 0 to 1. You should multiply them by the height and width of the texture to get the actual pixel locations on the texture itself.

Thank you for the replies. I’m starting to suspect that the issue might be that the Parent Mesh is scaled to 1.28 so as to cover the 128 pixel sprite that is a child of it. Since i grab my texture point from that mesh and then try to apply it to the sprite, maybe that is why I’m getting bad results the further away from center that I am. I’ll keep at it, and post the solution when i find it.

I missed the fact that you were dealing with a Sprite. This might help: Calculating position on a sprite on raycasthit - Questions & Answers - Unity Discussions

Ok I was able to get it to work, however i did not use raycast.
instead I created a grid of textures to cover screen using screencoord to do this (so 0,0 was in bottom left of screen). The calculation does rely on the sprite itself having a Pivot of bottom left too.

 if (sr == null) sr = GetComponent<SpriteRenderer>();
        float pixelWidth = sr.sprite.rect.width;
        float pixelHeight = sr.sprite.rect.height;
        float unitsToPixels = 100f;
        Debug.Log("Cell name=" + name);
      

        Pos = transform.InverseTransformPoint(Pos);

        int xPixel, yPixel;

        xPixel = (int)Mathf.RoundToInt(Pos.x * unitsToPixels);
        yPixel = (int)Mathf.RoundToInt(Pos.y * unitsToPixels);

xPixel and yPixel is equal to the pixel coord of the sprite where the Pos is (Pos is sent to the method and is the world coord of the pixel spot i am targeting).