threejs模型UV算法,超级好用

https://stackoverflow.com/questions/20774648/three-js-generate-uv-coordinate

使用模型表面法线来决定使用(xyz)中的哪两个,对应到UV坐标当中。用起来相当不错。当然如果能在设计模型的时候进行展UV就更好了。

The other answers here were a great help but didn't quite fit my requirements to apply a repeating pattern texture to all sides of a shape with mostly flat surfaces. The problem is that using only the x and y components as u and v results in weird stretched textures on vertical surfaces.

My solution below uses surface normals to pick which two components (x, y and z) to map to u and v. It's still pretty crude but it works quite well.

function assignUVs(geometry) {

    geometry.faceVertexUvs[0] = [];

    geometry.faces.forEach(function(face) {

        var components = ['x', 'y', 'z'].sort(function(a, b) {
            return Math.abs(face.normal[a]) > Math.abs(face.normal[b]);
        });

        var v1 = geometry.vertices[face.a];
        var v2 = geometry.vertices[face.b];
        var v3 = geometry.vertices[face.c];

        geometry.faceVertexUvs[0].push([
            new THREE.Vector2(v1[components[0]], v1[components[1]]),
            new THREE.Vector2(v2[components[0]], v2[components[1]]),
            new THREE.Vector2(v3[components[0]], v3[components[1]])
        ]);

    });

    geometry.uvsNeedUpdate = true;
}

函数并不会自动适配模型的大小进行贴图,用在多模型共用一张材质的时候效果更好,因为是基于物体实际三维坐标来做模型uv对应的。对于材质来讲,应该设置重复以及缩放比例来更好地表现。

This function doesn't normalise the UVs to the size of the object. This works better when applying the same texture to different sized objects in the same scene. However depending on the size of your world coordinate system, you'll probably need to scale and repeat the texture as well:

texture.repeat.set(0.1, 0.1);
texture.wrapS = texture.wrapT = THREE.MirroredRepeatWrapping;

 

posted @ 2018-01-09 22:38  $JackChen  阅读(8001)  评论(2编辑  收藏  举报