实现思路:
在片元着色器采样时,增加一个随时间变化的偏移值,由于uv是一个二维向量所以加的偏移值也需要一个二维向量。注意:在Laya的 shader中除了0,输入其它数字必须输入带有小数的数字,否则报错 。
"void main()\n" +"{\n" +"vec2 v = vec2(u_time * u_speed,0);\n"+"gl_FragColor=texture2D(u_Texture0, v_Texcoord + v) ;\n" +"}";
实现效果如下:
shader代码:
//所有的attributeMap属性var attributeMap = {'a_Position': Laya.VertexElementUsage.POSITION0,'a_Texcoord': Laya.VertexElementUsage.TEXTURECOORDINATE0, };//所有的uniform属性var uniformMap ={'u_MvpMatrix': [Laya.Sprite3D.MVPMATRIX, Laya.Shader3D.PERIOD_SPRITE], 'u_Texture0': [1, Laya.Shader3D.PERIOD_MATERIAL],'u_time':[22,Laya.Shader3D.PERIOD_SCENE],'u_speed':[4,Laya.Shader3D.PERIOD_MATERIAL],};var customShader = Laya.Shader3D.nameKey.add("CustomShader")var VS ="attribute vec4 a_Position;\n" +"uniform mat4 u_MvpMatrix;\n" +"attribute vec2 a_Texcoord;\n"+"varying vec2 v_Texcoord;\n" +"void main()\n" +"{\n" +"v_Texcoord = a_Texcoord;\n" +"gl_Position = u_MvpMatrix * a_Position;\n" +"}\n";var FS ="#ifdef FSHIGHPRECISION\n" +"precision highp float;\n" +"#else\n" +"precision mediump float;\n" +"#endif\n" +"varying vec2 v_Texcoord;\n" +"uniform sampler2D u_Texture0;\n"+ "uniform float u_time;\n"+"uniform float u_speed;\n" +"void main()\n" +"{\n" +"vec2 v = vec2(u_time * u_speed,0);\n"+"gl_FragColor=texture2D(u_Texture0, v_Texcoord + v) ;\n" +"}";Laya.ShaderCompile3D.add(customShader, VS, FS, attributeMap, uniformMap);}
调用代码:
CustomMat.initShader();var mat = new CustomMat();mat.setTexture(Laya.Texture2D.load("res/layabox.png"));mat.setSpeed(1);mat.blend = Laya.BaseMaterial.BLEND_ENABLE_SEPERATE;mesh.meshRender.sharedMaterial = mat;