Get Texture color value at ray collision point

Hi

I got a problem. I’m using “pickWithRay” to detect my collision. All works great.

I need to know what color of a texture is in collision point.

if (pickInfo && pickInfo.hit) {
    console.log(pickInfo.getTextureCoordinates());
    console.log(pickInfo.pickedMesh.material.diffuseTexture);
}

And what now? How to take a pixel color value from that texture at those UV coordinates :expressionless: I’m stuck :expressionless:

You need to get the pixel data of the texture and use the uv coordinates to read the right location inside it (multiply the uv by the width/height of the texture first).

You can use Texture.readPixels to get the texture data.

a simple example of how to take this from the buffer?

Once you have the buffer, it will be something like:

red = buffer[Math.floor(uv.x * (textureWidth - 1)) * 4 +
            Math.floor(uv.y * (textureHeight - 1)) * textureWidth * 4];
green = buffer[Math.floor(uv.x * (textureWidth - 1)) * 4 +
            Math.floor(uv.y * (textureHeight - 1)) * textureWidth * 4 + 1];
blue = buffer[Math.floor(uv.x * (textureWidth - 1)) * 4 +
            Math.floor(uv.y * (textureHeight - 1)) * textureWidth * 4 + 2];
alpha = buffer[Math.floor(uv.x * (textureWidth - 1)) * 4 +
            Math.floor(uv.y * (textureHeight - 1)) * textureWidth * 4 + 3];

If the texture is y inverted, you may need to use (1 - uv.y) instead of uv.y.

1 Like