MatterJS

      Eva.js 基于 Matterjs 的物理引擎,目前只接入了小部分内容,如需更多内容,可持续接入。

      Install

      使用 NPM

      1. npm install @eva/plugin-matterjs

      在浏览器中

      1. <script src=https://unpkg.com/@eva/plugin-matterjs@1.2.x/dist/EVA.plugin.renderer.matterjs.min.js></script>

      使用

      1. import {Physics} from ‘@eva/plugin-matterjs’;
      2. // 1.安装物理引擎后引入
      3. import {PhysicsSystem, Physics, PhysicsType} from ‘@eva/plugin-matterjs’;
      4. // 2.在Eva.js中注册插件
      5. const game = new Game({
      6. autoStart: true,
      7. frameRate: 60,
      8. systems: [
      9. new RendererSystem({
      10. transparent: true,
      11. canvas: canvasNode,
      12. backgroundColor: 0xfee79d,
      13. width: 750,
      14. height: 1624,
      15. resolution: 2,
      16. }),
      17. new GraphicsSystem(),
      18. new PhysicsSystem({
      19. resolution: 2, // 保持RendererSystem的resolution一致
      20. // isTest: true, // 是否开启调试模式
      21. // element: document.getElementById(‘game-container’), // 调试模式下canvas节点的挂载点
      22. world: {
      23. gravity: {
      24. y: 2, // 重力
      25. },
      26. },
      27. mouse: {
      28. open: true,
      29. },
      30. }),
      31. new TextSystem(),
      32. new ImgSystem(),
      33. new EventSystem(),
      34. ],
      35. });
      36. // 3.新建游戏实体对象
      37. const box = new GameObject(‘box’, {
      38. size: {
      39. width: 75,
      40. height: 75,
      41. },
      42. position: {
      43. x: 75 + Math.random() * 300,
      44. y: 75,
      45. },
      46. // origin 会映射为物理系统的质心,二维环境下即物理的几何中心,此处必须固定为 {x:0.5,y:0.5}
      47. origin: {
      48. x: 0.5,
      49. y: 0.5,
      50. },
      51. });
      52. // 4.给游戏对象添加Componet
      53. const physics = box.addComponent(
      54. new Physics({
      55. type: PhysicsType.RECTANGLE,
      56. bodyOptions: {
      57. isStatic: false, // 物体是否静止,静止状态下任何作用力作用于物体都不会产生效果
      58. restitution: 0.8,
      59. frictionAir: 0.1,
      60. friction: 0,
      61. frictionStatic: 0,
      62. force: {
      63. x: 0,
      64. y: 0,
      65. },
      66. },
      67. stopRotation: true, // 默认false,通常不用设置
      68. }),
      69. );
      70. //目前支持的碰撞事件 collisionStart collisionActive collisionEnd
      71. //刚体事件 tick,beforeUpdate,afterUpdate,beforeRender,afterRender,afterTick 通常使用beforeUpdate和afterUpdate即可
      72. physics.on(‘collisionStart’, (gameObject1, gameObject2) => {});
      73. console.log(“physics”,physics);

      参数

      type PhysicsType

      碰撞包围盒的形状

      • RECTANGLE 矩形
      • CIRCLE 圆形
      • POLYGON 等边多边形

      sides

      当type为 POLYGON 的时候,设置包围盒的边数

      radius

      当 type 为 POLYGONCIRCLE 时的半径

      bodyOptions

      相关属性,可参考 Matterjs官网

      ,