Successfully removing physics body on mousedown in Matter JS

So I finally got the mouse to access the body to remove it. Next step is to check to see if the value in the body matches the value in the question. Also gotta clean up the arrays once I remove the body to make sure I don’t introduce any “off by one” errors into the code.

Here’s the code for removing a body from the Matter.World.remove(world, body):

  
// - - - - - - - - - - - - - - - - -
// Sets up mouse constraints
// - - - - - - - - - - - - - - - - -

var mouseConstraint = Matter.MouseConstraint.create(engine, {
    element: canvas,
    constraint: {
        render: {
            visible: false
        },
        stiffness: 0.8
    }
});

Matter.World.add(world, mouseConstraint);

// Keep track of the mouse state
var mouseIsDown = false;

Matter.Events.on(mouseConstraint, 'mousedown', function (event) {
    var body = mouseConstraint.body;
    var ballId = body.id;
    var ballValue = balls[ballId - 1];
    console.log("mouse down on body with id:" + " " + ballId);
    console.log("ball value is:" + " " + ballValue);
    var mousePosition = event.mouse.position;
    mp = mousePosition;
    mouseIsDown = true;

    // Removes the body from the world
    Matter.World.remove(world, body);
});

Matter.Events.on(mouseConstraint, 'mouseup', function (event) {
    // console.log("mouseup called");
    var mousePosition = event.mouse.position;
    mp = mousePosition;
    mouseIsDown = false;
});
  

Leave a comment

Your email address will not be published. Required fields are marked *