Three.js着色器,如何使用alpha地图纹理以及不透明度和渐变。

huangapple go评论62阅读模式
英文:

Three js shader, how to use alpha map texture with opacity and gradient

问题

关于使渐变和 alpha 贴图纹理的不透明度生效的问题,您需要在片段着色器中正确处理 alpha 值。目前的片段着色器混合了颜色 color1color2,但没有正确处理 alpha 值。要解决这个问题,您可以修改片段着色器如下:

uniform vec3 color1;
uniform vec3 color2;
uniform sampler2D alphaMap;
varying vec2 vUv;

void main() {
  vec4 texel = texture2D(alphaMap, vUv);
  vec3 color = mix(color1, color2, vUv.y);
  gl_FragColor = vec4(color, texel.r);
}

通过将 gl_FragColor 中的 alpha 值设置为 texel.r,您可以确保使用 alpha 贴图中的 alpha 值来控制不透明度,从而正确显示纹理的透明部分。

这个修改应该可以解决问题,让黑色部分变为透明而不是白色。

英文:

Need help to make opacity work on shader with gradient and alpha map texture.
With code below results are next: gradient is working but opacity is not.

Three.js着色器,如何使用alpha地图纹理以及不透明度和渐变。

This is my alpha texture
Three.js着色器,如何使用alpha地图纹理以及不透明度和渐变。

and this is a geometry and material

const geometry = new THREE.BoxGeometry(32, 32);
const material = new THREE.ShaderMaterial({

uniforms: {
 transparent: true,
 alphaMap: { value: alphaTexture },
 color1: {
  value: new THREE.Color("purple")
 },
 color2: {
  value: new THREE.Color("red")
 }
},
vertexShader: `
varying vec2 vUv;

void main() {
  vUv = uv;
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
uniform vec3 color1;
uniform vec3 color2;
uniform sampler2D alphaMap;
varying vec2 vUv;

void main() {
  float alpha = texture2D(alphaMap, vUv).r;
  vec3 color = mix(color1, color2, vUv.y);
  gl_FragColor = vec4(color, alpha);
}
`,
});

as you can see, the black part of the texture is becoming white, but has to be transparent.

答案1

得分: 3

确保 transparent: true 属性位于您的 uniforms 对象之外:

uniforms: {
 // alphamap, color1, color2
},
transparent: true,
英文:

Make sure the transparent: true property is outside your uniforms object:

uniforms: {
 // alphamap, color1, color2
},
transparent: true,

huangapple
  • 本文由 发表于 2023年2月19日 00:17:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75494659.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定