How to get the texture co-ordinate(x,y) from a 3D point on the mesh renderer?

Hi all,

I am trying to find a point x,y on the texture, corresponding to a 3D point on the mesh.

Thanks in Advance.

You have to raycast against the mesh to find the point on the surface. The raycast already returns the texture coordinates at this point in the RaycastHit struct.

The only alternative would be to iterate through all triangles manually and test if the point is inside it’s bounds. If you really want to do this you have to project the point onto the triangle plane (unless you’re sure it is exactly on the surface) and then convert the point into barycentric coordinates. Now you can interpolate the uv from the 3 vertices uvs.

edit

Ok so it seems you want the texture coordinates of a collision point, right?

In this case it’s quite simple:

// Attached to your "ball / projectile"

void OnCollisionEnter(Collision collisionInfo)
{
    foreach (ContactPoint cp in collisionInfo.contacts)
    {
        RaycastHit hit;
        float rayLength = 0.1f;
        Ray ray = new Ray(cp.point - cp.normal * rayLength * 0.5f, cp.normal);
        Color C = Color.white; // default color when the raycast fails for some reason ;)
        if (cp.otherCollider.Raycast(ray, out hit, rayLength))
        {
            Texture2D tex = (Texture2D)cp.otherCollider.renderer.material.mainTexture;
            C = tex.GetPixelBilinear(hit.textureCoord.x, hit.textureCoord.y);
        }
        // Instantiate your effect and
        // use the color C
    }
}

Or, if you want to attach the script to the cube, it should look like this:

// Attached to your cube object

private Texture2D m_MainTexture;

void Start()
{
    m_MainTexture = (Texture2D)renderer.mainTexture;
}

void OnCollisionEnter(Collision collisionInfo)
{
    foreach (ContactPoint cp in collisionInfo.contacts)
    {
        RaycastHit hit;
        float rayLength = 0.1f;
        Ray ray = new Ray(cp.point + cp.normal * rayLength * 0.5f, -cp.normal);
        Color C = Color.white; // default color when the raycast fails for some reason ;)
        if (cp.thisCollider.Raycast(ray, out hit, rayLength))
        {
            C = m_MainTexture.GetPixelBilinear(hit.textureCoord.x, hit.textureCoord.y);
        }
        // Instantiate your effect and
        // use the color C
    }
}

ps: I haven’t tried it, so maybe the normal points the other way, but usually it points away from the “other object”.