Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PhaserJS: add physics to graphic objects

Most examples use sprites to add physics, but I want to add physics to objects created using the Graphics class. For example:

var square = game.add.graphics( 0, 0 );
//some definitions

game.physics.arcade.enable( square );

This doesn't work at all with graphics, but it does right away with sprites. Why is that and how can I achieve this?

Thanks in advance.

like image 936
René Olivo Avatar asked Feb 14 '23 01:02

René Olivo


1 Answers

I had to investigate quite a bit since it seems this is not the standard (at least tutorial wise), but you have to create a BitmapData object and use canvas to draw the figures. This is not nearly as fun as using game.add.graphics to create circles and poligons, etc. but it works well.

This is how you create a platform:

//creates the BitmapData object, you can use it to create figures:
var floor = game.add.bitmapData( 400, 20 ); //width, height

//this fills the whole object with a color:
floor.fill( 200, 100, 0, 1 ); //Red, Green, Blue, Alpha
//floor will have a canvas context object to draw figures. 
//Here are some more examples:
//http://www.html5canvastutorials.com/tutorials/html5-canvas-circles/

//after you finish drawing, you need to convert the object to a sprite:
var floorSprite = game.add.sprite( 100, 500, floor );

//this adds physics to the object and adds a .body property:
game.physics.arcade.enable( floorSprite );

//stops the object in place and prevents other objects from displacing it:
floorSprite.body.allowGravity   = false;
floorSprite.body.immovable      = true;

And that's how you can create a platform without having to rely on image files. I have seen a few tutorials using files instead of generating the platform and I think it's such a waste.

Also, I think you need to convert your vector to a bitmap is because vector physics is quite heavy on the hardware (or so it seems).

Hope this can help a few more people!

like image 188
René Olivo Avatar answered Feb 15 '23 19:02

René Olivo