I have a Matter.js World where I'm updating some Bodies.
let ball1 = document.getElementById("ball-1");
let ball2 = document.getElementById("ball-2");
let ball3 = document.getElementById("ball-3");
// module aliases
var Engine = Matter.Engine,
Render = Matter.Render,
World = Matter.World,
Bodies = Matter.Bodies,
Body = Matter.Body,
Events = Matter.Events;
// create an engine
var engine = Engine.create();
var w = window.innerWidth;
var h = window.innerHeight;
// create 3 circles and walls
var circle1 = Bodies.circle(w/2, 40, ball1.offsetWidth/2, { restitution: 0.99 });
var circle2 = Bodies.circle(w/2, 100, ball2.offsetWidth/2, { restitution: 0.99 });
var circle3 = Bodies.circle(w/2, 50, ball3.offsetWidth/2, { restitution: 0.99 });
var ceiling = Bodies.rectangle(w/2, -15, w, 30, { isStatic: true });
var wallLeft = Bodies.rectangle(-15, h/2, 30, h, { isStatic: true, restitution: 0.99 });
var wallRight = Bodies.rectangle(w+15, h/2, 30, h, { isStatic: true, restitution: 0.99 });
var floor = Bodies.rectangle(w/2, h+15, w, 30, { isStatic: true, restitution: 0.99 });
// add all of the bodies to the world
World.add(engine.world, [circle1, circle2, circle3, floor, wallLeft, wallRight, ceiling]);
Engine.run(engine);
Events.on(engine, "afterUpdate", function(){
ball1.style.transform = "translateX(" + circle1.position.x + "px) translateY(" + circle1.position.y + "px) rotate("+circle1.angle+"rad)";
ball2.style.transform = "translateX(" + circle2.position.x + "px) translateY(" + circle2.position.y + "px) rotate("+circle2.angle+"rad)";
ball3.style.transform = "translateX(" + circle3.position.x + "px) translateY(" + circle3.position.y + "px) rotate("+circle3.angle+"rad)";
});
The problem I'm having is that when I'm resizing the window, I'm calling the following method:
window.addEventListener("resize", () => {
w = window.innerWidth;
h = window.innerHeight;
Body.set(circle1, { x: w/2, y: 10 });
Body.set(circle2, { x: w/2 + 10, y: 10 });
Body.set(circle3, { x: w/2 - 10, y: 10 });
Body.set(floor, { x: w/2, width: w, y: h+15 });
Body.set(ceiling, { x: w/2, width: w });
Body.set(wallLeft, { y: h/2, height: h });
Body.set(wallRight, { x: w+15, y: h/2, height: h });
console.log(floor.y);
});
But, while the console.log
is showing the new y
position of the floor, the elements on screen aren't updating. Am I calling this function wrong?
Body.set(floor, { x: w/2, width: w, y: h+15 });
Full demo: https://codepen.io/EightArmsHQ/pen/9fe08dd4365f63666be2e53a676642c7
This question is a bit old, but if anyone has the same question, I'd better answer this.
In matter-js
update position using
Matter.Body.set(circle1, "position", {x: 100, y: 100})
Source code link : https://github.com/liabru/matter-js/blob/e909b0466cea2051267bab92a38ccaa9bf7f154e/src/body/Body.js#L222