一个案例:请点击这里查看物理模型的添加案例。
简介
Physijs
开发时的目标就是尽可能保持简单和用户友好。普通物理引擎的使用有可能使人望而却步,有想当多的复杂配置和选项,让人感觉不知所措。而Physijs
则将所有额外的逻辑抽象出来,以便您可以专注于项目的其余部分。
基础使用
它是Three.js
的一个插件,是一个友好的菜鸟级WebGL
框架。因此,您需要使用Three.js
来进行场景管理才能使用Physijs
。如果你对Three.js
不熟悉,那么花上几天的时间学习并回来再次查看文档, 如果你知道Three.js
的基础知识,那么你也已经了解了Physijs
的基础知识。
你如何添加Physijs到你的项目?只需六个简单的步骤:
- 将
<script>
标签添加到您的页面并将其指向该physi.js
文件。
<script type="text/javascript" src="physi.js"></script>
- 配置
Physijs.scripts.worker
和Physijs.scripts.ammoJavaScript
参数以指向Web Worker
和Ammo.js
脚本
Physijs.scripts.worker = 'physijs_worker.js';
Physijs.scripts.ammo = 'examples/js/ammo.js';
- 使用
Physijs.Scene
代替THREE.Scene
scene = new Physijs.Scene();
- 相反的
THREE.Mesh
,选择最好的物理网等Physijs.BoxMesh
(物理立方体),Physijs.SphereMesh
(物理球体)或Physijs.ConvexMesh
(物理凸面体)
// 场景内添加一个立方体
box = new Physijs.BoxMesh(
new THREE.CubeGeometry(5, 5, 5),
new THREE.MeshBasicMaterial({color: 0x888888})
);
scene.add(box);
scene.simulate
在渲染时或在想要迭代物理设置时调用该方法。
render = function () {
scene.simulate(); //调用物理引擎
renderer.render(scene, camera); // 渲染场景
requestAnimationFrame(render);
};
注意,因为Physijs
在与主应用程序分开的线程中(web Workers)运行,所以scene.simulate
完全可以在渲染场景之前进行调用。发生这种情况时,scene.simulate
会返回false
。
案例代码
<!doctype html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Physijs基本设置</title>
<style>
*{
margin: 0;
padding: 0;
}
canvas{
display: block;
}
</style>
<script type="text/javascript" src="examples/js/three.min.js"></script>
<script type="text/javascript" src="physi.js"></script>
</head>
<body>
<div id="viewport"></div>
</body>
<script type="text/javascript">
'use strict';
Physijs.scripts.worker = 'physijs_worker.js';
Physijs.scripts.ammo = 'examples/js/ammo.js';
var initScene, render, renderer, scene, camera, box;
initScene = function () {
renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setSize(window.innerWidth, window.innerHeight);
document.getElementById('viewport').appendChild(renderer.domElement);
scene = new Physijs.Scene();
camera = new THREE.PerspectiveCamera(
35,
window.innerWidth / window.innerHeight,
1,
1000
);
camera.position.set(60, 50, 60);
camera.lookAt(scene.position);
scene.add(camera);
// 场景内添加一个立方体
box = new Physijs.BoxMesh(
new THREE.CubeGeometry(5, 5, 5),
new THREE.MeshBasicMaterial({color: 0x888888})
);
scene.add(box);
requestAnimationFrame(render);
};
render = function () {
scene.simulate(); //调用物理引擎
renderer.render(scene, camera); // 渲染场景
requestAnimationFrame(render);
};
window.onload = initScene();
</script>
</html>