admin管理员组

文章数量:1410724

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.

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.

Share Improve this question edited May 4, 2014 at 17:37 René Olivo asked May 4, 2014 at 6:11 René OlivoRené Olivo 1811 silver badge12 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

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./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!

maybe it works with this:

anySprite.addChild(yourGraphicsObject);

and after that:

game.physics.arcade.enable( anySprite );

本文标签: javascriptPhaserJS add physics to graphic objectsStack Overflow