Three.js进阶篇之8 - Physijs物理引擎

Three.js可以通过使用Physijs库向场景中加入物理效果。这个库是基于著名的物理引擎ammo.js。


Physiji

1.导入库文件

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. Physijs.scripts.worker = 'js/Physijs/physijs_worker.js';  
  2. Physijs.scripts.ammo = 'js/Physijs/ammo.js';  

两个属性分别指向要执行的任务线程和ammo.js库。

2.创建带有物理效果的场景

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. var scene = new Physijs.Scene();  
  2. scene.setGravity(new THREE.Vector3(0,-10,0));  

使用setGravity()函数设置重力大小为y轴负方向,大小为10。

3.将原来场景的对象用Physiji库包装起来

原场景:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. var geometry = new THREE.CubeGeometry(100, 100, 100);  
  2. var material = new THREE.MeshBasicMaterial({});  
  3. var mesh = new THREE.Mesh(geometry,material);  

物理场景:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. var geometry = new THREE.CubeGeometry(100, 100, 100);  
  2. var material = new Physijs.createMaterial(new THREE.MeshPhongMaterial({  
  3.         restitution:0.5,  
  4.         friction:0.5  
  5.     }))  
  6. var mesh = new Physijs.BoxMesh(geometry,material,1);  

  物理场景材质增添了restitution(弹性形变)和friction(摩擦系数)两个参数。

  物理场景创建的对象增添了第三个参数   1:可以正常运动   0:困定(类似于墙体)   默认值:1

  物理场景还对基本的网格对象进行了覆盖详见Physijs API
4.渲染物理场景

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. function render(){  
  2.     requestAnimationFrame(render);  
  3.     renderer.render(scene, camera);  
  4.     scene.simulate();  
  5. }  

猜你喜欢

转载自blog.csdn.net/allenjiao/article/details/79564037
今日推荐