18:00学了一下着色器编程,23:00写出第一个效果,悟性还是太差。
这个效果可以做出来很多的应用,比如说发光的围栏,逐渐扩大的光束等等。
以下代码直接粘贴至BG即可运行:
var createScene = function () {
// This creates a basic Babylon Scene object (non-mesh)
var scene = new BABYLON.Scene(engine);
// This creates and positions a free camera (non-mesh)
var camera = new BABYLON.ArcRotateCamera("Camera", 0, 0, 4, new BABYLON.Vector3(0, 0, 0), scene);
// This positions the camera
camera.setPosition(new BABYLON.Vector3(0, 3, 10));
// This attaches the camera to the canvas
camera.attachControl(canvas, true);
// This creates a light, aiming 0,1,0 - to the sky (non-mesh)
var light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(0, 1, 0), scene);
// Default intensity is 1. Let's dim the light a small amount
light.intensity = 0.7;
// Our built-in 'sphere' shape.
var box = BABYLON.MeshBuilder.CreateBox("box", {size: 1}, scene);
// Move the sphere upward 1/2 its height
box.position.y = 1;
// Our built-in 'ground' shape.
var ground = BABYLON.MeshBuilder.CreateGround("ground", {width: 6, height: 6}, scene);
BABYLON.Effect.ShadersStore["customVertexShader"]= `
precision highp float;
// Attributes
attribute vec3 position;
attribute vec2 uv;
// Uniforms
uniform mat4 worldViewProjection;
uniform float time;
// Varying
varying vec2 vUV;
void main(void) {
gl_Position = worldViewProjection * vec4(position, 1.0);
vUV = uv;
}
`;
BABYLON.Effect.ShadersStore["customFragmentShader"]= `
precision highp float;
varying vec2 vUV;
uniform sampler2D textureSampler;
uniform float time;
void main(void) {
vec4 a1 = texture2D(textureSampler, vec2(vUV.x-time,vUV.y));
//gl_FragColor = vec4(a1.r,a1.g,a1.b,a1.a);
// R/G/B 手动设置,设置为红色
gl_FragColor = vec4(187.0/255.0,70./255.,75.0/250.0,a1.a);
}
` ;
var shaderMaterial = new BABYLON.ShaderMaterial("shader", scene, {
vertex: "custom",
fragment: "custom",
},
{
needAlphaBlending: true,
attributes: ["position", "normal", "uv"],
uniforms: ["world", "worldView", "worldViewProjection", "view", "projection"]
});
var mainTexture = new BABYLON.Texture("https://www.iios.com.cn/iios-minio/bljs/tmp/wall.png", scene);
shaderMaterial.setTexture("textureSampler", mainTexture);
shaderMaterial.setFloat("time", 0);
shaderMaterial.setVector3("cameraPosition", BABYLON.Vector3.Zero());
shaderMaterial.backFaceCulling = false;
box.material = shaderMaterial;
//box.material.hasAlpha = true;
var plane2 = BABYLON.MeshBuilder.CreatePlane("plane2", {}, scene);
plane2.material = shaderMaterial;
plane2.position.x = 1.5;
plane2.position.y = 1;
var time = 0;
console.log(plane2.material)
engine.runRenderLoop(function () {
plane2.scaling.x +=0.005
plane2.scaling.y +=0.005
var shaderMaterial = scene.getMaterialByName("shader");
shaderMaterial.setFloat("time", time);
time += 0.02;
shaderMaterial.setVector3("cameraPosition", scene.activeCamera.position);
scene.render();
});
return scene;
};