引言
在开始之前,我们还是要解释下什么是 cannon.js 以及它的作用。
cannon.js 是一个 3d 物理引擎,通过为物体赋予真实的物理属性的方式来计算运动、旋转和碰撞检测。cannon.js 相较于其他常见的物理引擎来说,比较轻量级而且完全通过 javascript 来实现。
cannon.js 的官方文档地址为 schteppe.github.io/cannon.js/ ,从官方介绍中也可以看到很多有趣的例子,如下所示:

本篇,我们就尝试用 three.js + cannon.js 做一个简单的示例。
首先我们通过 three.js 创建一个球及一个平面,前面已经介绍过很多关于 three.js 如何使用,这里就不多做介绍了
大体代码及效果
const sphere = new three.mesh(
new three.spheregeometry(1, 20, 20),
new three.meshstandardmaterial()
);
scene.add(sphere);
const floor = new three.mesh(
new three.planegeometry(20, 20),
new three.meshstandardmaterial()
);
floor.position.y = -5;
floor.rotation.x = -math.pi / 2;
scene.add(floor);

在开始正式使用物理引擎之前,我们需要先弄清一些概念,three.js 是渲染引擎,cannon.js 是物理引擎。渲染引擎负责画 ui,而物理引擎负责运动。

我们通过物理引擎打造一个和当前 ui 一样的世界,然后让引擎运动起来,然后将运动物体的坐标实时反映到渲染引擎中,这样使得物理引擎和渲染引擎协同工作。
cannon.js 打造当前 ui
所以第一步,利用 cannon.js 打造和当前 ui 一样的物理世界
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 floorshape = new cannon.plane();
const floorbody = new cannon.body();
// 当质量为0时,使得物体保持不动
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);
如此便打造了一个和 ui 一样的物理世界,代码很简单,相信通过注释就能明白做了什么事情。
下面就是让物理引擎“动起来”,并将物体的坐标同步赋值给渲染引擎中的物体。
从文档中可以看到,step 就是我们想要的方法,利用 step 更新物理引擎世界的物体,随后将 spherebody 的 position 赋值给 three.js 中的 sphere。

const clock = new three.clock();
function render() {
// 更新物理引擎世界的物体
world.step(1 / 60, clock.getdelta());
sphere.position.copy(spherebody.position);
controls.update();
renderer.render(scene, camera);
// 渲染下一帧的时候就会调用 render 函数
requestanimationframe(render);
}
render();
如此便实现了 three.js 和 cannon.js 的联动,最终效果如下图所示:

以上就是three.js引入cannon.js及使用示例详解的详细内容,更多关于three.js 引入cannon.js的资料请关注代码网其它相关文章!
发表评论