Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Also send events to the top body in a multipart body #9

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

getkey
Copy link

@getkey getkey commented Feb 25, 2020

When the body is multipart, the event didn't get sent to the top body.

@TomYeoman
Copy link

Nice PR this helped me!

You need to call all handlers (your code only handles onCollide, but not end)

const Matter = require("matter-js");

const MatterCollisionEvents = {
  name: "matter-collision-events",
  version: "0.1.5",
  for: "matter-js@^0.12.0",
  install: function(matter) {
    // add the onCollide, onCollideEnd, and onCollideActive callback handlers
    // to the native Matter.Body created

    function triggerRecursively(body, eventName, pair) {
      matter.Events.trigger(body, eventName, { pair: pair });

      if (eventName === "onCollide") {
        body._mceOC &&
          body._mceOC(pair);
      }

      if (eventName === "onCollideActive") {
        body._mceOCA &&
          body._mceOCA(pair);
      }

      if (eventName === "onCollideEnd") {
        body._mceOCE &&
          body._mceOCE(pair);
      }

      if (body.parent !== undefined && body.parent !== body) {
        triggerRecursively(body.parent, eventName, pair);
	  }
    }

    function sendEvent(pair, eventName) {
      triggerRecursively(pair.bodyA, eventName, pair);
      triggerRecursively(pair.bodyB, eventName, pair);
    }

    var create = matter.Body.create;
    matter.Body.create = function() {
      var body = create.apply(null, arguments);
      body.onCollide = function(cb) { body._mceOC = cb; };
      body.onCollideEnd = function(cb) { body._mceOCE = cb; };
      body.onCollideActive = function(cb) { body._mceOCA = cb; };
      return body;
    };
    matter.after("Engine.create", function() {
      matter.Events.on(this, "collisionStart", function(event) {
        event.pairs.map(function (pair) {
          sendEvent(pair, "onCollide");
        });
      });

      matter.Events.on(this, "collisionActive", function(event) {
        event.pairs.map(function (pair) {
          sendEvent(pair, "onCollideActive");
        });
      });

      matter.Events.on(this, "collisionEnd", function(event) {
        event.pairs.map(function (pair) {
          sendEvent(pair, "onCollideEnd");
        });
      });
    });
  },
};


module.exports = {MatterCollisionEvents};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants