Three.js物理引擎
本篇文章将围绕物理引擎,让物体有更加真实的现实效果的感觉,主要使用的物理引擎为CANNON
小球弹跳
基础代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 300 );
camera.position.set(0, 0, 18); scene.add(camera);
const renderer = new THREE.WebGLRenderer({ alpha: true });
renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement);
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
const axesHelper = new THREE.AxesHelper(5); scene.add(axesHelper);
function render() { renderer.render(scene, camera); requestAnimationFrame(render); }
render();
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight); renderer.setPixelRatio(window.devicePixelRatio); });
|
添加一个球和平面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| const sphereGeometry = new THREE.SphereGeometry(1, 20, 20); const sphereMaterial = new THREE.MeshStandardMaterial(); const sphere = new THREE.Mesh(sphereGeometry, sphereMaterial); scene.add(sphere);
const floor = new THREE.Mesh( new THREE.PlaneBufferGeometry(20, 20), new THREE.MeshStandardMaterial() );
floor.position.set(0, -5, 0); floor.rotation.x = -Math.PI / 2; scene.add(floor);
|
打光
1 2 3 4 5 6 7
|
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5); scene.add(ambientLight);
const dirLight = new THREE.DirectionalLight(0xffffff, 0.5); scene.add(dirLight);
|
添加阴影
1 2 3 4 5 6 7 8
| dirLight.castShadow = true;
floor.receiveShadow = true;
sphere.castShadow = true;
renderer.shadowMap.enabled = true;
|
物理世界
要实现一个小球掉落效果,需要在物理世界添加一个物理小球,并且和renderer中的绑定
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| import * as CANNON from "cannon-es";
const world = new CANNON.World();
world.gravity.set(0, -9.8, 0);
const sphereShape = new CANNON.Sphere(1);
const sphereWorldMaterial = new CANNON.Material();
const sphereBody = new CANNON.Body({ shape: sphereShape, position: new CANNON.Vec3(0, 0, 0), mass: 1, material: sphereWorldMaterial, });
world.addBody(sphereBody);
const clock = new THREE.Clock(); function render() { let deltaTime = clock.getDelta(); world.step(1 / 120, deltaTime); sphere.position.copy(sphereBody.position); renderer.render(scene, camera); requestAnimationFrame(render); }
|
添加物理地面
我们刚才创建了一个物理小球,但是这个小球会落到我们的地面下面去,那是因为我们的地面并不是物理的才导致的,接下来我们写一个物理的地面
1 2 3 4 5 6 7 8 9 10 11
| const floorShape = new CANNON.Plane(); const floorBody = new CANNON.Body();
floorBody.mass = 0; floorBody.addShape(floorShape);
floorBody.position.set(0, -5, 0);
floorBody.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), -Math.PI / 2); world.addBody(floorBody);
|
添加掉落音效
这里的音效可以找爱给网的音效,里面有非常多好用的素材(这里自己大家自己尝试,博客里面音效不是很好放出来)
1 2 3 4 5 6 7 8 9
| const hitSound = new Audio("assets/metalHit.mp3");
function HitEvent(e) { const impactStrength = e.contact.getImpactVelocityAlongNormal(); hitSound.play(); } sphereBody.addEventListener("collide", HitEvent);
|
让小球多次回弹
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| const sphereWorldMaterial = new CANNON.Material("sphere");
const sphereBody = new CANNON.Body({ shape: sphereShape, position: new CANNON.Vec3(0, 0, 0), mass: 1, material: sphereWorldMaterial, });
const floorMaterial = new CANNON.Material("floor"); floorBody.material = floorMaterial;
const defaultContactMaterial = new CANNON.ContactMaterial( sphereMaterial, floorMaterial, { friction: 0.1, restitution: 0.7, } );
world.addContactMaterial(defaultContactMaterial);
|
小球回弹添加音效
刚才我们将小球变得可以回弹了,但是他的声音依旧只有一个,我们可以根据小球的强度来播放音效(这里一样不放了)
碰撞强度大于2,就将之前的音效清零,重新播放
1 2 3 4 5 6 7 8 9 10 11
| function HitEvent(e) { const impactStrength = e.contact.getImpactVelocityAlongNormal(); console.log(impactStrength); if (impactStrength > 2) { hitSound.currentTime = 0; hitSound.play(); } }
|
完整代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
| import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import gsap from "gsap";
import * as dat from "dat.gui";
import * as CANNON from "cannon-es";
console.log(CANNON);
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 300 );
camera.position.set(0, 0, 18); scene.add(camera);
const sphereGeometry = new THREE.SphereGeometry(1, 20, 20); const sphereMaterial = new THREE.MeshStandardMaterial(); const sphere = new THREE.Mesh(sphereGeometry, sphereMaterial); sphere.castShadow = true; scene.add(sphere);
const floor = new THREE.Mesh( new THREE.PlaneBufferGeometry(20, 20), new THREE.MeshStandardMaterial() );
floor.position.set(0, -5, 0); floor.rotation.x = -Math.PI / 2; floor.receiveShadow = true; scene.add(floor);
const world = new CANNON.World(); world.gravity.set(0, -9.8, 0);
const sphereShape = new CANNON.Sphere(1);
const sphereWorldMaterial = new CANNON.Material("sphere");
const sphereBody = new CANNON.Body({ shape: sphereShape, position: new CANNON.Vec3(0, 0, 0), mass: 1, material: sphereWorldMaterial, });
world.addBody(sphereBody);
const hitSound = new Audio("assets/metalHit.mp3");
function HitEvent(e) { const impactStrength = e.contact.getImpactVelocityAlongNormal(); console.log(impactStrength); if (impactStrength > 2) { hitSound.currentTime = 0; hitSound.play(); } } sphereBody.addEventListener("collide", HitEvent);
const floorShape = new CANNON.Plane(); const floorBody = new CANNON.Body(); const floorMaterial = new CANNON.Material("floor"); floorBody.material = floorMaterial;
floorBody.mass = 0; floorBody.addShape(floorShape);
floorBody.position.set(0, -5, 0);
floorBody.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), -Math.PI / 2); world.addBody(floorBody);
const defaultContactMaterial = new CANNON.ContactMaterial( sphereMaterial, floorMaterial, { friction: 0.1, restitution: 0.7, } );
world.addContactMaterial(defaultContactMaterial);
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5); scene.add(ambientLight); const dirLight = new THREE.DirectionalLight(0xffffff, 0.5); dirLight.castShadow = true; scene.add(dirLight);
const renderer = new THREE.WebGLRenderer({ alpha: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
document.body.appendChild(renderer.domElement);
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
const axesHelper = new THREE.AxesHelper(5); scene.add(axesHelper);
const clock = new THREE.Clock();
function render() { let deltaTime = clock.getDelta(); world.step(1 / 120, deltaTime);
sphere.position.copy(sphereBody.position);
renderer.render(scene, camera); requestAnimationFrame(render); }
render();
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight); renderer.setPixelRatio(window.devicePixelRatio); });
|
立方体碰撞
基础代码和上面是一样的,这里就不贴了
创建立方体
将小球换成立方体即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| const cubeGeometry = new THREE.BoxBufferGeometry(1, 1, 1); const cubeMaterial = new THREE.MeshStandardMaterial(); const cube = new THREE.Mesh(cubeGeometry, cubeMaterial); cube.castShadow = true; scene.add(cube);
const cubeWorldMaterial = new CANNON.Material("cube");
const cubeShape = new CANNON.Box(new CANNON.Vec3(0.5, 0.5, 0.5));
const cubeBody = new CANNON.Body({ shape: cubeShape, position: new CANNON.Vec3(0, 0, 0), mass: 1, material: cubeWorldMaterial, });
world.addBody(cubeBody);
const defaultContactMaterial = new CANNON.ContactMaterial( cubeWorldMaterial, floorMaterial, { friction: 0.1, restitution: 0.7, } );
|
通过点击创建立方体
先封装一个方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| const cubeArr = [];
const cubeWorldMaterial = new CANNON.Material("cube");
function createCube() { const cubeGeometry = new THREE.BoxBufferGeometry(1, 1, 1); const cubeMaterial = new THREE.MeshStandardMaterial(); const cube = new THREE.Mesh(cubeGeometry, cubeMaterial); cube.castShadow = true; scene.add(cube); const cubeShape = new CANNON.Box(new CANNON.Vec3(0.5, 0.5, 0.5));
const cubeBody = new CANNON.Body({ shape: cubeShape, position: new CANNON.Vec3(0, 0, 0), mass: 1, material: cubeWorldMaterial, }); cubeBody.applyLocalForce( new CANNON.Vec3(300, 0, 0), new CANNON.Vec3(0, 0, 0) );
world.addBody(cubeBody); function HitEvent(e) { const impactStrength = e.contact.getImpactVelocityAlongNormal(); console.log(impactStrength); if (impactStrength > 2) { hitSound.currentTime = 0; hitSound.volume = impactStrength / 12; hitSound.play(); } } cubeBody.addEventListener("collide", HitEvent); cubeArr.push({ mesh: cube, body: cubeBody, }); }
|
点击监听
1
| window.addEventListener("click", createCube);
|
渲染
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| function render() { let deltaTime = clock.getDelta(); world.step(1 / 120, deltaTime);
cubeArr.forEach((item) => { item.mesh.position.copy(item.body.position); item.mesh.quaternion.copy(item.body.quaternion); });
renderer.render(scene, camera); requestAnimationFrame(render); }
|
添加外部力
1 2 3 4
| cubeBody.applyLocalForce( new CANNON.Vec3(300, 0, 0), new CANNON.Vec3(0, 0, 0) );
|
声音的强弱
1
| hitSound.volume = impactStrength / 12;
|
完整代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
| import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import gsap from "gsap";
import * as dat from "dat.gui";
import * as CANNON from "cannon-es";
console.log(CANNON);
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 300 );
camera.position.set(0, 0, 18); scene.add(camera);
const cubeArr = [];
const cubeWorldMaterial = new CANNON.Material("cube");
function createCube() { const cubeGeometry = new THREE.BoxBufferGeometry(1, 1, 1); const cubeMaterial = new THREE.MeshStandardMaterial(); const cube = new THREE.Mesh(cubeGeometry, cubeMaterial); cube.castShadow = true; scene.add(cube); const cubeShape = new CANNON.Box(new CANNON.Vec3(0.5, 0.5, 0.5));
const cubeBody = new CANNON.Body({ shape: cubeShape, position: new CANNON.Vec3(0, 0, 0), mass: 1, material: cubeWorldMaterial, }); cubeBody.applyLocalForce( new CANNON.Vec3(300, 0, 0), new CANNON.Vec3(0, 0, 0) );
world.addBody(cubeBody); function HitEvent(e) { const impactStrength = e.contact.getImpactVelocityAlongNormal(); console.log(impactStrength); if (impactStrength > 2) { hitSound.currentTime = 0; hitSound.volume = impactStrength / 12; hitSound.play(); } } cubeBody.addEventListener("collide", HitEvent); cubeArr.push({ mesh: cube, body: cubeBody, }); }
window.addEventListener("click", createCube);
const floor = new THREE.Mesh( new THREE.PlaneBufferGeometry(20, 20), new THREE.MeshStandardMaterial() );
floor.position.set(0, -5, 0); floor.rotation.x = -Math.PI / 2; floor.receiveShadow = true; scene.add(floor);
const world = new CANNON.World(); world.gravity.set(0, -9.8, 0);
const hitSound = new Audio("assets/metalHit.mp3");
const floorShape = new CANNON.Plane(); const floorBody = new CANNON.Body(); const floorMaterial = new CANNON.Material("floor"); floorBody.material = floorMaterial;
floorBody.mass = 0; floorBody.addShape(floorShape);
floorBody.position.set(0, -5, 0);
floorBody.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), -Math.PI / 2); world.addBody(floorBody);
const defaultContactMaterial = new CANNON.ContactMaterial( cubeWorldMaterial, floorMaterial, { friction: 0.1, restitution: 0.7, } );
world.addContactMaterial(defaultContactMaterial);
world.defaultContactMaterial = defaultContactMaterial;
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5); scene.add(ambientLight); const dirLight = new THREE.DirectionalLight(0xffffff, 0.5); dirLight.castShadow = true; scene.add(dirLight);
const renderer = new THREE.WebGLRenderer({ alpha: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
document.body.appendChild(renderer.domElement);
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
const axesHelper = new THREE.AxesHelper(5); scene.add(axesHelper);
const clock = new THREE.Clock();
function render() { let deltaTime = clock.getDelta(); world.step(1 / 120, deltaTime);
cubeArr.forEach((item) => { item.mesh.position.copy(item.body.position); item.mesh.quaternion.copy(item.body.quaternion); });
renderer.render(scene, camera); requestAnimationFrame(render); }
render();
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight); renderer.setPixelRatio(window.devicePixelRatio); });
|