Three.js中AlphaMap与Map共用UV导致同步位移问题如何解决?
解决Three.js r142中MeshPhongMaterial的map与alphaMap同步位移问题
问题本质是:MeshPhongMaterial的map和alphaMap默认共用模型的第一组UV坐标(UV0)。当你修改colorTex的offset时,相当于对UV0的采样位置做了偏移,alphaMap同样基于UV0采样,所以会跟着同步位移,导致遮罩和颜色纹理一起移动。
下面是两种可行的解决方法:
方法一:添加独立UV组(推荐)
给几何体新增第二组UV,让alphaMap使用这组固定的UV,和map的UV彻底分开:
var tl = new THREE.TextureLoader(); var colorTex = tl.load('./env_half.png'); var alphaTex = tl.load('./glass_mask.png'); var planeGeometry = new THREE.PlaneBufferGeometry(20, 10); // 复制原UV数据,创建第二组UV(uv2) planeGeometry.setAttribute('uv2', planeGeometry.attributes.uv.clone()); colorTex.offset.setX(0.2); // 现在只影响颜色纹理的采样 var planeMaterial = new THREE.MeshPhongMaterial({ side: THREE.DoubleSide, transparent: true, map: colorTex, alphaMap: alphaTex, alphaMapUV: 1, // 指定alphaMap用第二组UV(索引1对应uv2) });
这样map用UV0,alphaMap用UV1,两者采样完全独立,修改颜色纹理的偏移不会影响遮罩位置。
方法二:自定义着色器(进阶)
如果需要更灵活的控制,可以修改着色器代码,单独给颜色纹理加偏移:
const phongShader = THREE.ShaderLib.phong; const customMaterial = new THREE.ShaderMaterial({ uniforms: { ...phongShader.uniforms, map: { value: colorTex }, alphaMap: { value: alphaTex }, colorOffset: { value: new THREE.Vector2(0.2, 0) }, }, vertexShader: phongShader.vertexShader, fragmentShader: ` uniform vec2 colorOffset; ${phongShader.fragmentShader.replace( 'vec4 diffuseColor = texture2D( map, vUv );', 'vec4 diffuseColor = texture2D( map, vUv + colorOffset );' )} `, side: THREE.DoubleSide, transparent: true, });
这种方式复用了Phong着色器的原有逻辑,只修改颜色纹理的采样步骤,alpha纹理保持原始UV采样,不受偏移影响。
内容的提问来源于stack exchange,提问作者James
相关产品推荐
相关产品推荐

