1 当你一步一步的看完博客之后,你将从一只脆弱的蚂蚁变成一只强壮的蚂蚁,这一章我们将会创建粒子,也就是俗称精灵的东西:
1.1 第一种写法,Three.js自带的,也就是不用shader的
直接代码咯:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="../../core/WebglManager.js"></script>
<script src="../../core/three.js"></script>
<script src="../../core/BasicElementCreater.js"></script>
</head>
<body>
<script>
window.onload = function (ev) {
createGLCanvas();
//加载贴图
var textureLoader = new THREE.TextureLoader();
var sprite1 = textureLoader.load( 'textures/snowflake2.png' );
//创建粒子管理器
var sp =createSprite(sprite1);
function update(ev) {
//转webgl坐标
var mouse = screen2WebglCoordinate(ev,800,800);
//转视口坐标
var viewPort = screenConvertToWorld(mouse);
//生成粒子
for (var i = 0;i<30;i++)
{
sp.updateVerticesBuf(Vector3((Math.random()-0.5)*0.1+viewPort.x,(Math.random()-0.5)*0.1+viewPort.y,0),1024);
}
//更新位置
sp.updateParticalWithRandom(0.1);
}
glCanvas.onmousemove = function(ev){
update(ev);
}
}
</script>
</body>
</html>
核心的sp生成代码:
function createSprite(sprite) {
var spMaster = {};
var materials = new THREE.PointsMaterial( { size: 1, map: sprite, blending: THREE.AdditiveBlending, depthTest: false, transparent: true } );
var geometry = new THREE.BufferGeometry();
var particles = new THREE.Points( geometry, materials );
//添加到场景里面
addObject(particles);
spMaster.material =materials;
spMaster.geometry =geometry;
spMaster.partical = particles;
spMaster.verticalBuffer = [];
spMaster.index = 0;
spMaster.updateVectircesPos = function(value,i){
spMaster[i] += value;
}
spMaster.updateParticalWithRandom = function(value){
for(var i in spMaster.verticalBuffer){
spMaster.verticalBuffer[i] += (Math.random() - 0.5)*value;
}
}
spMaster.updateVertices = function () {
var positionAttribute = new THREE.Float32BufferAttribute(spMaster.verticalBuffer, 3 );
geometry.addAttribute( 'position', positionAttribute );
}
spMaster.updateVerticesBuf = function(vector3,len){
spMaster.verticalBuffer[spMaster.index*3+0]=(vector3.x);
spMaster.verticalBuffer[spMaster.index*3+1]=(vector3.y);
spMaster.verticalBuffer[spMaster.index*3+2]=(vector3.z);
spMaster.index++;
if(spMaster.index>len)
{
spMaster.index = 0;
}
spMaster.updateVertices();
}
return spMaster;
}