threejs 物理引擎cannon自学

概述

cannon.js

基本描述

  • 受three.js和ammon.js的启发,加上网络缺乏物理引擎,cannon.js应运而生。
    Inspired by three.js and ammo.js, and driven by the fact that the web lacks a physics engine, here comes cannon.js.

  • 受three.js和ammon.js的启发,再加上网络缺乏物理引擎,cannon.js应运而生。

  • 刚体物理引擎包括简单的碰撞检测、各种体型、接触、摩擦和约束。
    Inspired by three.js and ammo.js, and driven by the fact that the web lacks a physics engine, here comes cannon.js. The rigid body physics engine includes simple collision detection, various body shapes, contacts, friction and constraints.

  • 比 Ammo.js 更加轻量级,使用起来更舒服

演示代码使用

下面的示例代码在平面上创建一个球体,逐步进行模拟,并将球体模拟打印到控制台
请注意,Cannon.js使用国际单位制(米、千克、秒等)

// Setup our world - 创建一个物理世界,重力为 -9.82
var world = new CANNON.World();
world.gravity.set(0, 0, -9.82); // m/s²

// Create a sphere - 创建一个球体,质量为5kg,半径大小1米,添加到物理世界
var radius = 1; // m
var sphereBody = new CANNON.Body({
   mass: 5, // kg
   position: new CANNON.Vec3(0, 0, 10), // m
   shape: new CANNON.Sphere(radius) //-- 形状为球体
});
world.addBody(sphereBody);

// Create a plane - 创建一个质量为0的台子,形状为平面,添加到物理世界
var groundBody = new CANNON.Body({
    mass: 0 // mass == 0 makes the body static
});
var groundShape = new CANNON.Plane(); //-- 形状为平面
groundBody.addShape(groundShape);
world.addBody(groundBody);

var fixedTimeStep = 1.0 / 60.0; // seconds
var maxSubSteps = 3;

// Start the simulation loop - 启动模拟循环
var lastTime;
(function simloop(time){
  requestAnimationFrame(simloop);
  if(lastTime !== undefined){
     var dt = (time - lastTime) / 1000;
     world.step(fixedTimeStep, dt, maxSubSteps);
  }
  console.log("Sphere z position: " + sphereBody.position.z);
  lastTime = time;
})();

学习资源

  • 官方示例地址 - https://schteppe.github.io/cannon.js/
  • 文档地址 - https://schteppe.github.io/cannon.js/docs/
  • github地址 - https://github.com/schteppe/cannon.js
cannon-es.js - (优先看)

基本描述

  • 一个轻量级且简单的网络三维物理引擎
  • 主要由一个开发者维护,还在维护的cannon-es仓库
  • cannon-es 克隆了原仓库并致力于长期更新维护新的仓库,cannon-es 用法和 Cannon.js 用法是完全一致

学习资源

  • 官方示例地址 - https://pmndrs.github.io/cannon-es/
  • 文档地址 - https://pmndrs.github.io/cannon-es/docs/index.html
  • npm地址 - https://www.npmjs.com/package/cannon-es

待学习

https://juejin.cn/post/7200039970575941693#heading-7 - 实例参考 - (优先看)
https://schteppe.github.io/cannon.js/ - cannon引擎官方
https://juejin.cn/post/7121739944199995399 - 物理引擎种类优劣以及cannon引擎使用流程
https://pmndrs.github.io/cannon-es/ - cannon引擎demo

未完待续....

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容