How to put a video on a body, Matter.js
Asked Answered
F

1

1

How to make a video attached to a matter.js body/composite?

var body = Bodies.circle(
    Common.random(10, render.options.width), 
    Common.random(10, render.options.height),
    radius,
    {
        render: {
            sprite: {
                texture: 'jaime.mp4'
            }
        },
        mass: Common.random(150, 160),
        frictionAir: 0,
        plugin: {
            attractors: [
                MatterAttractors.Attractors.gravity
            ],
            wrap: {
                min: { x: 0, y: 0 },
                max: { x: render.options.width, y: render.options.height }
            }
        }
    }
)
World.add(world, body);
};

when I see render it, I don't see anything but a blank black body.

Finella answered 21/11, 2021 at 21:44 Comment(0)
F
1

As described in greater detail in a few other posts such as Using Matter.js to render to the DOM or React and Matter.js Text inside a rectangle, Matter.js' built-in renderer is for simple demonstration, debugging and prototyping use cases. For most applications beyond that, you'll want to use a custom renderer that has the flexibility to handle things like video.

For example, HTML5 is a fantastically flexible renderer that lets you plug MJS physics into arbitrary elements. Video is no problem:

const engine = Matter.Engine.create();
const box = {
  body: Matter.Bodies.rectangle(150, 0, 128, 72),
  elem: document.querySelector("#box"),
  render() {
    const {x, y} = this.body.position;
    this.elem.style.top = `${y - 36}px`;
    this.elem.style.left = `${x - 64}px`;
    this.elem.style.transform = `rotate(${this.body.angle}rad)`;
  },
};
const ground = Matter.Bodies.rectangle(
  200, 200, 400, 120, {isStatic: true}
);
const mouseConstraint = Matter.MouseConstraint.create(
  engine, {element: document.body}
);
Matter.Composite.add(
  engine.world, [box.body, ground, mouseConstraint]
);
(function rerender() {
  box.render();
  Matter.Engine.update(engine);
  requestAnimationFrame(rerender);
})();
#box {
  position: absolute;
  background: #111;
  height: 72px;
  width: 128px;
  top: -130px;
  left: -130px;
  cursor: move;
}

#ground {
  position: absolute;
  background: #666;
  top: 140px;
  height: 120px;
  width: 400px;
}

html, body {
  position: relative;
  height: 100%;
  margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.20.0/matter.min.js"></script>
<div id="box">
  <video width="128" muted autoplay>
    <source src="https://upload.wikimedia.org/wikipedia/commons/b/b5/Slow_Motion_Salad_-_Sony_FS700.webm" type="video/webm">
    Your browser does not support HTML video.
  </video>
</div>
<div id="ground"></div>
Fugitive answered 3/7, 2022 at 22:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.