Skip to content

Commit

Permalink
added body removal to Example.remove
Browse files Browse the repository at this point in the history
  • Loading branch information
liabru committed Nov 25, 2023
1 parent 6d10c3d commit 1209e88
Showing 1 changed file with 23 additions and 10 deletions.
33 changes: 23 additions & 10 deletions examples/remove.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,11 @@ Example.remove = function() {
Events = Matter.Events;

// create engine
var engine = Engine.create(),
world = engine.world;
var engine = Engine.create({
enableSleeping: true
});

var world = engine.world;

// create renderer
var render = Render.create({
Expand All @@ -24,6 +27,7 @@ Example.remove = function() {
width: 800,
height: 600,
showAngleIndicator: true,
showSleeping: true
}
});

Expand All @@ -33,9 +37,6 @@ Example.remove = function() {
var runner = Runner.create();
Runner.run(runner, engine);

var stack = null,
lastTimestamp = 0;

var createStack = function() {
return Composites.stack(20, 20, 10, 5, 0, 0, function(x, y) {
var sides = Math.round(Common.random(1, 8));
Expand All @@ -61,15 +62,28 @@ Example.remove = function() {
});
};

// add and remove stacks every few updates
var stack = null,
bottomStack = createStack(),
lastTimestamp = 0;

// add and remove bodies and composites every few updates
Events.on(engine, 'afterUpdate', function(event) {
// limit rate
if (stack && event.timestamp - lastTimestamp < 800) {
if (event.timestamp - lastTimestamp < 800) {
return;
}

lastTimestamp = event.timestamp;

// remove an old body
Composite.remove(bottomStack, bottomStack.bodies[0]);

// add a new body
Composite.add(
bottomStack,
Bodies.rectangle(Common.random(100, 500), 50, Common.random(25, 50), Common.random(25, 50))
);

// remove last stack
if (stack) {
Composite.remove(world, stack);
Expand All @@ -82,10 +96,9 @@ Example.remove = function() {
Composite.add(world, stack);
});

// add another stack that will not be removed
Composite.add(world, createStack());

Composite.add(world, [
bottomStack,

// walls
Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),
Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),
Expand Down

0 comments on commit 1209e88

Please sign in to comment.