如何在WebGL中使纹理在y轴和x轴上移动



对于这个项目,我试图将纹理(以1024x2048 png发送的雨滴图像(向下移动到屏幕上,然后在像素到达画布底部后将其循环回到屏幕顶部。一旦像素到达顶部,我还想将其向右移动一点,经过几次迭代,它将到达画布的最左侧,然后发送到画布的最右侧。然而,我似乎无法使它正常工作。由于我对WebGL的了解非常有限,我不确定我做错了什么,也不确定我应该问什么是正确的问题。我很确定这是我如何移动像素的问题,但我不知道我应该做什么。

这是我的顶点着色器:

<script id="vertex-shader1" type="x-shader/x-vertex">
attribute  vec4 vPosition;
attribute vec2 vTexCoord;
varying vec2 fTexCoord;
void main() 
{
	float y= vTexCoord.y - float(0.01);
	float x= vTexCoord.x;
	
	if(y < float(0.0)) {
		y = float(1.0);
		//x = fTexCoord.x + float(0.1) ;
	}
/*	if(x > float(1.0)){
		x = float(0.0);
	}
*/	
gl_Position = vPosition;
	fTexCoord= vec2(x,y);
} 
</script>

这是我的碎片着色器:

<script id="fragment-shader1" type="x-shader/x-fragment">
precision mediump float;
uniform sampler2D texture1;
varying vec2 fTexCoord;
void
main()
{
//	gl_FragColor = texture2D(texture1, vec2(x,y)); 
	
	gl_FragColor= texture2D(texture1, fTexCoord);
}
</script>

上面的着色器应该使图像中的雨滴(链接在下面(在屏幕上向下移动。雨滴.png

但相反,它只是把雨滴伸出来。(它这样做:messedup_rainls.png(

关于如何解决这个问题有什么想法吗?

听起来你想"滚动"一个纹理。要做到这一点,只需将偏移传递给纹理坐标即可。您可以在片段或顶点着色器中执行此操作

有效

uniform vec2 offset;
vec2 newTexCoords = texCoords + offset;

然后随时间改变offset。偏移值通常只需要在0到1的范围内,因为过去的事情只会重复。

示例:

const vs = `
attribute vec4 position;
attribute vec2 texcoord;
uniform vec2 offset;
varying vec2 v_texcoord;
void main() {
gl_Position = position;
v_texcoord = texcoord + offset;
}
`;
const fs = `
precision mediump float;
varying vec2 v_texcoord;
uniform sampler2D tex;
void main() {
gl_FragColor = texture2D(tex, v_texcoord);
}
`;
const gl = document.querySelector('canvas').getContext('webgl');
// compile shaders, link program, lookup locations
const programInfo = twgl.createProgramInfo(gl, [vs, fs]);
const bufferInfo = twgl.createBufferInfoFromArrays(gl, {
position: {
numComponents: 2,
data: [
-1, -1,
1, -1,
-1,  1,
-1,  1,
1, -1,
1,  1,
],
},
texcoord: {
numComponents: 2,
data: [
0,  1,
1,  1,
0,  0,
0,  0,
1,  1,
1,  0,
],
},
});
const texture = twgl.createTexture(gl, {
src: 'https://i.imgur.com/ZKMnXce.png',
crossOrigin: 'anonymous',
});
function render(time) {
time *= 0.001;  // convert to seconds

gl.useProgram(programInfo.program);
// bind buffers and set attributes
twgl.setBuffersAndAttributes(gl, programInfo, bufferInfo);
// set uniforms and bind textures
twgl.setUniforms(programInfo, {
tex: texture,
offset: [(time * .5) % 1, (time * .6) % 1],
});
const count = 6;
gl.drawArrays(gl.TRIANGLES, 0, count);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
canvas { border: 1px solid black; }
<canvas></canvas>
<script src="https://twgljs.org/dist/4.x/twgl.js"></script>

如果你想要更灵活的东西,我建议你使用矩阵作为你的纹理坐标

uniform mat4 texMatrix;
vec2 newTexCoords = (texMatrix * vec4(texCoords, 0, 1)).xy;

这将使你可以像处理顶点坐标一样操作纹理坐标,这意味着你可以缩放纹理、旋转纹理、扭曲纹理等…你可以在这里看到使用纹理矩阵的例子

最新更新