Three.js案例从0到1创建组合对象并让它们动起来
Posted pocean2012
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Three.js案例从0到1创建组合对象并让它们动起来相关的知识,希望对你有一定的参考价值。
1. 创建对象,创建材质,并建立几何形状
//首先定义一个大海对象
Sea = function()
// 创建一个圆柱几何体
// 参数为:顶面半径,底面半径,高度,半径分段,高度分段
var geom = new THREE.CylinderGeometry(600, 600, 800, 40, 10);
// 在 x 轴旋转几何体
geom.applyMatrix(new THREE.Matrix4().makeRotationX(-Math.PI / 2));
// 创建材质
var mat = new THREE.MeshPhongMaterial(
color: Colors.blue,
transparent: true,
opacity: .6,
shading: THREE.FlatShading
);
// 为了在 Three.js 创建一个物体,我们必须创建网格用来组合几何体和一些材质
this.mesh = new THREE.Mesh(geom, mat);
// 允许大海对象接收阴影
this.mesh.receiveShadow = true;
2. 实例化,并添加到场景
sea = new Sea();
// 在场景底部
sea.mesh.position.y = -600;
// 添加大海的网格至场景
scene.add(sea.mesh);
3. 创建复杂的组合对象,比如飞机模型
// 创建飞机模型
var AirPlane = function()
this.mesh = new THREE.Object3D();
// 创建机舱
var geomCockpit = new THREE.BoxGeometry(60, 50, 50, 1, 1, 1);
var matCockpit = new THREE.MeshPhongMaterial(
color: Colors.red,
shading: THREE.FlatShading
);
var cockpit = new THREE.Mesh(geomCockpit, matCockpit);
cockpit.castShadow = true;
cockpit.receiveShadow = true;
this.mesh.add(cockpit);
// 创建引擎
var geomEngine = new THREE.BoxGeometry(20, 50, 50, 1, 1, 1);
var matEngine = new THREE.MeshPhongMaterial(
color: Colors.white,
shading: THREE.FlatShading
);
var engine = new THREE.Mesh(geomEngine, matEngine);
engine.position.x = 40;
engine.castShadow = true;
engine.receiveShadow = true;
this.mesh.add(engine);
// 创建机尾
var geomTailPlane = new THREE.BoxGeometry(15, 20, 5, 1, 1, 1);
var matTailPlane = new THREE.MeshPhongMaterial(
color: Colors.red,
shading: THREE.FlatShading
);
var tailPlane = new THREE.Mesh(geomTailPlane, matTailPlane);
tailPlane.position.set(-35, 25, 0);
tailPlane.castShadow = true;
tailPlane.receiveShadow = true;
this.mesh.add(tailPlane);
// 创建机翼
var geomSideWing = new THREE.BoxGeometry(40, 8, 150, 1, 1, 1);
var matSideWing = new THREE.MeshPhongMaterial(
color: Colors.red,
shading: THREE.FlatShading
);
var sideWing = new THREE.Mesh(geomSideWing, matSideWing);
sideWing.castShadow = true;
sideWing.receiveShadow = true;
this.mesh.add(sideWing);
// 创建螺旋桨
var geomPropeller = new THREE.BoxGeometry(20, 10, 10, 1, 1, 1);
var matPropeller = new THREE.MeshPhongMaterial(
color: Colors.brown,
shading: THREE.FlatShading
);
this.propeller = new THREE.Mesh(geomPropeller, matPropeller);
this.propeller.castShadow = true;
this.propeller.receiveShadow = true;
// 创建螺旋桨的桨叶
var geomBlade = new THREE.BoxGeometry(1, 100, 20, 1, 1, 1);
var matBlade = new THREE.MeshPhongMaterial(
color: Colors.brownDark,
shading: THREE.FlatShading
);
// 创建机翼
var blade = new THREE.Mesh(geomBlade, matBlade);
blade.position.set(8, 0, 0);
blade.castShadow = true;
blade.receiveShadow = true;
this.propeller.add(blade);
this.propeller.position.set(50, 0, 0);
this.mesh.add(this.propeller);
;
4. 在动画子程序中让海浪翻滚,让飞机螺旋桨动起来
//海浪效果
sea.mesh.rotation.z += .005;
//螺旋桨效果
airplane.propeller.rotation.x += 0.3;
5. 效果是这样子:
以上是关于Three.js案例从0到1创建组合对象并让它们动起来的主要内容,如果未能解决你的问题,请参考以下文章