Проверить Matter.js
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

61 行
1.5KB

  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();
  33. }
  34. function addObjects() {
  35. boxes.push(
  36. new Box(engine.world, 250, 20, 40, 40),
  37. new Box(engine.world, 300, 350, 40, 40),
  38. new Box(engine.world, 320, 70, 40, 40),
  39. new Box(engine.world, 0, 400, 800, 60, { isStatic: true })
  40. );
  41. }
  42. function gameLoop() {
  43. // update the physics world
  44. Matter.Engine.update(engine, 1000 / 60);
  45. // update the DOM world
  46. for (let b of boxes) {
  47. b.update();
  48. }
  49. requestAnimationFrame(() => this.gameLoop());
  50. }