I have made a class which allows you to create Box2D bodies for a object layer. I have made this because I have needed this myself and this would be a huge time saver for me and I hope for you also.
This class supports the following objects,
- Circle (You can create it with any shape set “Type” parameter to “Circle” and it creates a Circle fixture based on width as diameter)
- Polygon (Allowed only per 8 points, I you need more then you have to split it up)
How it works:
In you tmx editor you have to create a layer called “Collision” and make all the objects in that layer.
Change in TiledBodyCreator.cpp
#define PTMRATIO 64
To your ptmratio
Then in the game code you have to include TiledBodyCreator.h and after you have created Tilemap and Box2d world you can add this code which will create a body with all objects as fixtures in it and add it to world.
Here is a small preview of what I have tested
My tiled map in editor
My game with box2d debug
This is the code I have used
this->setAnchorPoint(Point::ZERO); b2Vec2 gravity; gravity.Set(0.0f, -10.0f); auto world = new b2World(gravity); world->SetAllowSleeping(false); auto debugLayer = B2DebugDrawLayer::create(world, 64); this->addChild(debugLayer, 9999); auto map = TMXTiledMap::create("Test.tmx"); map->setAnchorPoint(Point::ZERO); map->setPosition(0,0); this->addChild(map, 3); TiledBodyCreator::initCollisionMap(map, world); this->setScale(0.2f);
I hope this helped you a lot.
The classes are added to attachments of this post.
TiledPreview.PNG (147.8 KB)
GamePreview.PNG (37.7 KB)
TiledBodyCreator.zip (1.8 KB)
you can find the newer version of TiledBodyCreator here