Problems with Raycast and texture coordinates

hi everyone !

there is my problem :
i use a RaycastHit to know if my cursor is over my mesh collider.
If it is over, i need to know the texture coordinate in order to change the texture color.

Using textureCoord, I get a texture coordinate offset from my hit point and still hit the top of my texture.
Using textureCoord2, I still get the same texture coordinate either the right or the left side of my mesh.

Result, I am able to reach the upper half of my texture instead of the whole.

I checked my UV model with my 3D software, there is no problem.

Vector2 uv  = Vector2.zero;
Vector2 uv2 = Vector2.zero;
Ray mouseRay = new Ray();
Camera cam = Camera.main;
mouseRay = cam.ScreenPointToRay( Input.mousePosition );
float raySize = 10.0f;
RaycastHit hit;
if( m_meshCollider.Raycast( mouseRay, out hit, raySize )
{
    uv  = hit.textureCoord;
    uv2 = hit.textureCoord2;
}

I also tried with a shorter distance for raySize.

There is the code for calculating my X and Y coordinates on the texture.

m_brushSize = the size of the brush i want to apply on my texture.
The texture is a 256x256 texture.

int x = (int)(uv.x * 256) - m_brushSize / 2 - 1;
int y = (int)(uv.y * 256) - m_brushSize / 2 - 1;

int clampX = Mathf.Clamp( x, m_brushSize, texture.width - m_brushSize );
int clampY = Mathf.Clamp( y, m_brushSize, texture.height - m_brushSize );

Any idea ?

Hi, welcome to the forum!

Please can you explain your problem in some more detail? I’m not sure exactly what you are asking.

I’ll try to be clearer.

I use to know RaycastHit have information to do 2 things:

  1. snap an object on my model
  2. retrieve the texture coordinates on the model to change the color of the texture

I can snap my object on the model.

I have a concern with the second operation: the texture coordinates that returns the RaycastHit does not correspond to the position on my texture.
The texture has been applied so that the left side of the model corresponds to the upper part of the texture.
The right side of the model corresponds to the lower part of the texture.
When I am on the left side, I get the proper texture coordinates. When I’m on the right side, I get the texture coordinates corresponding to the left.

I try to fix this problem.

That explanation is it clearer?

I wonder if MeshCollider.Raycast could have a bug… Try doing the same thing with Physics.Raycast as a test (the parameters are the same, but it will cast the ray against other colliders too).

I found the problem. My FBX model has 7 UVMap. By reducing them to only one, the problem has disapeared.

Thanks for the concern !