I followed this tutorial用于为WebGL重新创建drawImage
,但它没有涉及的一件事是,对于具有透明像素的图像,例如游戏精灵,图像矩形后面的所有内容(即使像素都是透明的)都会被清除。
这可能是微不足道的,但我对GLSL完全不熟悉,这里是着色器:
fragment
precision mediump float;
varying vec2 v_texcoord;
uniform sampler2D u_texture;
void main() {
gl_FragColor = texture2D(u_texture, v_texcoord);
}
vertex
attribute vec4 a_position;
attribute vec2 a_texcoord;
uniform mat4 u_matrix;
varying vec2 v_texcoord;
void main() {
gl_Position = u_matrix * a_position;
v_texcoord = a_texcoord;
}
如何修改这些以避免在精灵的透明像素渲染到它们时隐藏已经渲染的帧中的像素?
我想到了。很难找到一个初学者,因为入门教程不解释很多重要的基础知识,比如你可以使用texture2D(u_texture, v_texcoord).a
来获取alpha,或者discard
不能绘制像素。
precision mediump float;
varying vec2 v_texcoord;
uniform sampler2D u_texture;
void main() {
vec4 color = texture2D(u_texture, v_texcoord);
float alpha = texture2D(u_texture, v_texcoord).a;
if (alpha < 1.0) {
discard;
}
gl_FragColor = color;
}