kittykatattack / hexi

Make games the fun way!
MIT License
551 stars 83 forks source link

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

Open gkjpettet opened 6 years ago

gkjpettet commented 6 years ago

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 commented 6 years ago

@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 commented 6 years ago

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 commented 6 years ago

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