Discontinuity in RaycastHit.textureCoord values (getting coordinates on texture right)

757 views Asked by At

Hi I'm trying to get a particular coordinate on texture (under mouse cursor). So on mouse event I'm performing:

Ray outRay = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit clickRayHit = new RaycastHit();

if (!Physics.Raycast(outRay, out clickRayHit))
{
    return;
}

Vector2 textureCoordinate = clickRayHit.textureCoord;

Texture2D objectTexture = gameObject.GetComponent<Renderer>().material.mainTexture as Texture2D;

int xCord = (int)(objectTexture.width * textureCoordinate.x);
int yCord = (int)(objectTexture.height * textureCoordinate.y);

But the problem is that the coordinate I'm getting is not preciesly under the cursor but "somewhat near it". And it's not like coordinates are consistently shifted in one way but shifting is not random as well. They are shifted differently in different points of the texture but: they remain somwhere in the area of real cursor and coordinates shifted in the same way when cursor is above the same point.

Here is part of coordinates log: http://pastebin.ca/3029357

If i haven't described problem good enough I can record a short screencast.

GameObject is a Plane.

If it is relevant mouseEvent is generated by windows mouseHook. (Application specific thing)

What am I doing wrong?

UPD: I've decided to record screencast - https://youtu.be/LC71dAr_tCM?t=42. Here you can see Paint window image through my application. On the bottom left corner you can see that Paint is displaying coordinates of the mouse (I'm getting this coordinates in a way I've described earlier - location of a point on a texture). So as I move mouse cursor you can see how coordinates are changing.

UPD2:
I just want to emphasize one more time that this shift is not constant or linear. There could be "jumps" around the mouse coordinates (but not only jumps). The video above explains it better.

1

There are 1 answers

0
Stvad On BEST ANSWER

So it was scaling problem after all. One of the scale values were negative and was causing this behaviour.