DOCTYPE html>
ceshititle>script>
}
style>
head>
div>
varcube= newArray(100);varcamera, scene, renderer;varid= null;
init();functioninit()
{
scene= newTHREE.Scene();
camera= newTHREE.PerspectiveCamera(45,
window.innerWidth/window.innerHeight,0.1,1000);
camera.position.x= 100;
camera.position.y= 100;
camera.position.z= 100;
camera.lookAt(scene.position);//创建一个WebGL渲染器并设置其大小
renderer= newTHREE.WebGLRenderer();
renderer.setClearColor(newTHREE.Color(0xEEEEEE));
renderer.setSize(window.innerWidth, window.innerHeight);varaxes= newTHREE.AxisHelper(200);
scene.add(axes);for(vari=0;i<100;i++)
{vargeometry= newTHREE.BoxGeometry(5,5,5);for(varj= 0; j
{varhex=Math.random()* 0xffffff;
geometry.faces[ j ].color.setHex( hex );
geometry.faces[ j+ 1].color.setHex( hex );
}varmaterial= newTHREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, overdraw:0.5} );
cube[i]= newTHREE.Mesh( geometry, material );
cube[i].position.x=Math.random()*100-50;
cube[i].position.y=Math.random()*100-50;
cube[i].position.z=Math.random()*100-50;
scene.add( cube[i] );
id=setInterval(render,33);
}functionrender()
{for(vari=0;i<100;i++)
{
cube[i].position.x+=Math.random()-0.5;
cube[i].position.y+=Math.random()-0.5;
cube[i].position.z+=Math.random()-0.5;if(Math.abs(cube[i].position.x)>100)
cube[i].position.x=0;if(Math.abs(cube[i].position.y)>100)
cube[i].position.y=0;if(Math.abs(cube[i].position.z)>100)
cube[i].position.z=0;
}
renderer.render( scene, camera );
}
document.getElementById("WebGL-output").appendChild(renderer.domElement);
}script>
body>
html>
这篇博客介绍了如何使用Three.js库创建一个包含100个方块的3D场景,每个方块随机运动。通过设置方块的位置和颜色,结合WebGLRenderer渲染,实现了一种动态的随机选取动画效果。同时,博客还展示了如何限制方块的运动范围,确保它们不会超出设定的边界。

被折叠的 条评论
为什么被折叠?



