今天讲threejs里比较复杂的一个功能,骨骼动画,骨骼动画也是应用场景很多的一种,因为无论是机器还是人都会存在骨骼动画,尤其是对设备或者人细节化的展示时候,以前的动画都是一个独立的模型进行移动或者旋转,但是物理世界中很多都是一个物体的移动是受制于另一个物体的,比如一个人的胳膊运动,大臂带动小臂,小臂上下摆动却不影响大臂,但是小臂的一头却固定在大臂上。
threejs中引入了bone来制作骨骼,不过要注意的是这个Bone并非是一个模型,而是指一个关节,这个不理解的话就很难理解骨骼动画了,比如一根圆柱形分为四段,大臂,小臂,手掌,手指,那么就需要5个节点,分别是肩膀处,胳膊肘,手腕,手指根部,手指尖部,然后移动或者旋转其中一个关节,会影响到边上的两段。
这里用threejs的代码实例,首先创建一个基础的3D场景:
initScene(){
scene = new THREE.Scene();
const axesHelper = new THREE.AxesHelper( 100 );
axesHelper.position.set(0,0,0)
scene.add( axesHelper );
},
initCamera(){
this.camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 10000);
this.camera.position.set(200,400,200);
},
initLight(){
//添加两个平行光
const directionalLight1 = new THREE.DirectionalLight(0xffffff, 1.5);
directionalLight1.position.set(300,300,300)
scene.add(directionalLight1);
const directionalLight2 = new THREE.DirectionalLight(0xffffff, 1.5);
directionalLight2.position.set(-300,300,300)
scene.add(directionalLight2);
},
initRenderer(){
this.renderer = new THREE.WebGLRenderer({ antialias: true });
this.container = document.getElementById("container")
this.renderer.setSize(this.container.clientWidth, this.container.clientHeight);
this.renderer.setClearColor('#AAAAAA', 1.0);
this.container.appendChild(this.renderer.domElement);
},
initControl(){
this.controls = new OrbitControls(this.camera, this.renderer.domElement);
this.controls.enableDamping = true;
this.controls.maxPolarAngle = Math.PI / 2.2; // // 最大角度
},
initAnimate() {
requestAnimationFrame(this.initAnimate);
this.renderer.render(scene, this.camera);
}