1,介绍
该示例使用的是 r95版本Three.js库。
主要实现功能:模拟开门关门动画。效果图如下:
2,动画主要说明
1,使用THREE.BoxGeometry创建几何体。
2,引用纹理THREE.TextureLoader进行材质创建THREE.MeshPhongMaterial
3,创建物体THREE.Mesh并引用几何体和材质
4,设置物体绕Y轴旋转实现动画,这里需要注意的是物体旋转是以自身中心进行旋转的,所以这里需要把几何体THREE.BoxGeometry平移自身宽度的一半,这样物体中心就是THREE.BoxGeometry几何体的边缘。
createDoor(100, 180, 2, 0, -700, 90, 700, "左门"); createDoor(100, 180, 2, 0, -500, 90, 700, "右门"); //创建门 function createDoor(width, height, depth, angle, x, y, z, name) { var loader = new THREE.TextureLoader(); var doorgeometry = new THREE.BoxGeometry(width, height, depth); var doormaterial_left = new THREE.MeshPhongMaterial({ map: loader.load("assets/textures/door_left.png") }); doormaterial_left.opacity = 1.0; doormaterial_left.transparent = true; var doormaterial_right = new THREE.MeshPhongMaterial({ map: loader.load("assets/textures/door_right.png") }); doormaterial_right.opacity = 1.0; doormaterial_right.transparent = true; var doormaterialArr = []; if (name.indexOf("左门") > -1) { // 设置偏移 doorgeometry.translate(50, 0, 0); doormaterialArr = [doormaterial_left, doormaterial_left, doormaterial_left, doormaterial_left, doormaterial_left, doormaterial_right ]; } else { // 设置偏移 doorgeometry.translate(-50, 0, 0); doormaterialArr = [doormaterial_right, doormaterial_right, doormaterial_right, doormaterial_right, doormaterial_right, doormaterial_left ]; } var door = new THREE.Mesh(doorgeometry, doormaterialArr); door.position.set(x, y, z); door.rotation.y += angle * Math.PI; //-逆时针旋转,+顺时针 door.name = name; scene.add(door); }
使用Tween.js实现动画, 监听键盘“O”键实现开门效果,“C”键实现关门效果
document.onkeydown = function(event) { var l1 = scene.getObjectByName("左门"); var r1 = scene.getObjectByName("右门"); // 打开 if (event.keyCode == 79) { new TWEEN.Tween({ lv: 0, rv: 0, }) .to({ lv: -0.5 * Math.PI, rv: 0.5 * Math.PI, }, 1000) .easing(TWEEN.Easing.Bounce.Out) .onUpdate(function() { l1.rotation.y = this.lv; r1.rotation.y = this.rv; }) .start(); } // 关闭 if (event.keyCode == 67) { new TWEEN.Tween({ lv: -0.5 * Math.PI, rv: 0.5 * Math.PI, }) .to({ lv: 0, rv: 0, }, 1000) .easing(TWEEN.Easing.Bounce.Out) .onUpdate(function() { l1.rotation.y = this.lv; r1.rotation.y = this.rv; }) .start(); } }
纹理素材如下