three.jstexturesuv-mapping

How to define the area of the texture to apply to a face


I have a cube made with Three.JS and I want to apply a part of a texture on each face. Concretely, I am looking for a function taking 4 parameters: x1, y1, x2, y2 specifying the area of the texture to apply to the face.
For example, with input [1, 0, 15, 16] (for a texture of 16x16), I want the face texture of right (left is my control cube, [0, 16, 0, 16])

Example of uv

If I specify [16, 0, 0, 16]`, my texture is flip.
I think I have to do that with UV (because is relative to the texture and not to the cube itself) but for the moment, I was not able to get a satisfactory result.

I also want that each face is independent. So if I modify the texture UV of one, the texture UV of the others is not modified (even if the texture is the same).

Here a minimal version of my cube (cleaned of all my tests and others things not relative to my issue): https://jsfiddle.net/theogiraudet/djcnrte0/

Thank you for your answer!


Solution

  • Texture coordinates go from 0,0 to 1,1 from bottom left to top right. A more detailed explanation of texture mapping is available on the discover three.js website

    Made a demo here:
    https://codepen.io/cdeep/pen/XWaXGYg?editors=0011

    The cube has 6 faces, 4 vertices, 2 coordinates each. The uv attribute is a BufferAttribute of size 48 which can be updated to control the corresponding part of the texture for each vertex.

    geometry.attributes.uv.copyArray(<Array of size 48>);
    geometry.attributes.uv.needsUpdate = true;
    

    In the codepen, I repeated the array to apply the same texture to each face.