Boldijar Paul
Boldijar Paul

Reputation: 5495

Libgdx - box2d- create custom polygonbody

I tried using this Libgdx and Box2D Draw a custom shape But it didn't helped me.

Let's say that I have a image - http://cdn.motocross.transworld.net/files/2010/09/geicohondausa2.png

I want to create convex polygons for the image and then display individual images for the fixtures/body.

Is that possible? sprite.getVertices won't work also..

Upvotes: 1

Views: 1261

Answers (2)

daniel
daniel

Reputation: 697

Sprite.getVertices() returns 20 floats, which contain X, Y, U, V and Color, so 5 * 4 = 20, you might get the index by using for example SpriteBatch.X1 for vertex at index 0 and SpriteBatch.Y1 Y2 or so, this is good because library may change.

Note that PolygonShape number of vertices in Box2d should be in range of 3 >= VERTICES <= 8, so you can't use more than 8, however you can use multiple Fixtures and use FixtureDef for every PolygonShape and attach to the body.

Also indices are important on PolygonShape, (however the new version of box2d does not care), and getting from Sprite vertices is good and is arranged.

Upvotes: 0

noone
noone

Reputation: 19776

A Sprite is always rectangular, that's why Sprite.getVertices() makes no sense here.

Using the editor in the linked question, you can create the body as a polygon. Then you have to export/import it in your game as a Body with the correct fixture(s). Probably you should also add some circle wheel fixtures and connect them with joints to the chassis.

You actually cannot add an image to a Body. Box2D knows nothing about rendering or visuals of any kind. You need to do that yourself. Using a SpriteBatch and a Sprite. All you need to do is keeping the sprite and the body synchronized in every frame before rendering the sprite. That means you do something like sprite.setPosition(body.getPosition()) and sprite.setRotation(body.getRotation()). (Just dummy code, you probably need some more conversions).

Upvotes: 1

Related Questions