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

Can Matter.js be integrated into a Hexi game? #44

Open
gkjpettet opened this issue Sep 26, 2017 · 3 comments
Open

Can Matter.js be integrated into a Hexi game? #44

gkjpettet opened this issue Sep 26, 2017 · 3 comments
Labels

Comments

@gkjpettet
Copy link

Is it possible to integrate a 2d rigid body physics engine into Hexi, specifically matter.js? Not sure if you have any experience in this area and just looking for a pointer in the right direction.

@kittykatattack
Copy link
Owner

kittykatattack commented Sep 26, 2017

@gkjpettet Yes!
I'm at this very moment working on a series of physics games using Hexi and MatterJS.
It's very easy to do:

  1. Create your MatterJS bodies and Hexi (or Pixi) sprites as usual.
  2. Create an array called physicsSprites
  3. Each Hexi sprite will have a matching MatterJS body. Add both of these to the physicsSprites array like this:

physicsSprites.push([matterJsBody, hexiSprite])

Then, inside your game loop (the play function), loop through all the bodies and sprites in the physicsSprites array. Set the sprite to match the position and rotation of its matching body:

function play() {

   phyicsSprites.forEach(element => {

    //Get a reference to the physics body and the sprite
    let body = element[0];
    let sprite = element[1];
     
    //Set the sprite to the body's position and rotation 
    sprite.x = body.position.x;
    sprite.y = body.position.y;
    sprite.rotation = body.angle;
  });

}

That's it!

I experimented with a few physics engines and overall found MatterJS to be the easiest to use, learn, and integrate into Hexi.

@kittykatattack
Copy link
Owner

Oh, there's one very important thing I forgot!

MatterJS's x/y alignment is to the centre of the body.
Hexi (and Pixi) sprites are aligned to the top left corner.
That means, for Hexi sprites to match the positions of the MatterJS bodies, you have to centre the x/y registration point on the Hexi sprites, like this:

anySprite.setPivot(0.5, 0.5);

@gkjpettet
Copy link
Author

Epic! Thanks for this! I'll get straight to tinkering. Thanks a lot for Hexi - it's really useful.

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

No branches or pull requests

2 participants