Проверить Matter.js
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.0KB

  1. class Box {
  2. constructor(world, x, y, w, h, options) {
  3. // add box to physics simulation
  4. this.physicsBox = Matter.Bodies.rectangle(x, y, w, h, options);
  5. Matter.Composite.add(world, this.physicsBox);
  6. // add DOM box at the same coordinates
  7. this.div = document.createElement("box");
  8. document.body.appendChild(this.div);
  9. this.div.style.width = w + "px";
  10. this.div.style.height = h + "px";
  11. this.width = w;
  12. this.height = h;
  13. this.update();
  14. }
  15. update() {
  16. let pos = this.physicsBox.position;
  17. let angle = this.physicsBox.angle;
  18. let degrees = angle * (180 / Math.PI);
  19. let x = this.physicsBox.bounds.min.x;
  20. let y = this.physicsBox.bounds.min.y;
  21. this.div.style.transform = `translate(${x}px, ${y}px) rotate(${degrees}deg)`;
  22. // old uses position
  23. // this.div.style.transform = `translate(${pos.x - this.width / 2}px, ${pos.y - this.height / 2 }px) rotate(${degrees}deg)`;
  24. }
  25. }
  26. let engine;
  27. let boxes = [];
  28. setupMatter();
  29. addObjects();
  30. gameLoop();
  31. function setupMatter() {
  32. engine = Matter.Engine.create({ enableSleeping: true });
  33. }
  34. function addObjects() {
  35. boxes.push(
  36. new Box(engine.world, 250, 20, 40, 40, { restitution: 0.8 }),
  37. new Box(engine.world, 300, 350, 40, 40, { restitution: 0.8 }),
  38. new Box(engine.world, 320, 70, 40, 40, { restitution: 0.8 }),
  39. new Box(engine.world, 0, 400, 1200, 60, { isStatic: true }),
  40. new Box(engine.world, 260, 50, 40, 40),
  41. new Box(engine.world, 330, 300, 40, 40),
  42. new Box(engine.world, 350, 170, 40, 40),
  43. new Box(engine.world, 160, 150, 40, 40),
  44. new Box(engine.world, 190, 300, 40, 40),
  45. new Box(engine.world, 250, 270, 40, 40),
  46. );
  47. }
  48. function gameLoop() {
  49. // update the physics world
  50. Matter.Engine.update(engine, 1000 / 60);
  51. var sleepingCount = 0;
  52. // update the DOM world
  53. for (let b of boxes) {
  54. b.update();
  55. if (b.physicsBox.isSleeping)
  56. {
  57. sleepingCount += 1;
  58. }
  59. }
  60. console.debug("sleeping count:", sleepingCount);
  61. requestAnimationFrame(() => this.gameLoop());
  62. }