Sunday, November 9, 2014

Creating Boundaries for our physics world

In the game i am making, i want my player to be inside a cage or locked room. To achieve this is pretty easy using physics:


auto edgeBody = PhysicsBody::createEdgeBox(visibleSize, PHYSICSBODY_MATERIAL_DEFAULT, METER_TO_PIXEL(1));
auto edgeNode = Node::create();
edgeNode->setPosition(Point(visibleSize.width/2,visibleSize.height/2));
edgeNode->setPhysicsBody(edgeBody);
this->addChild(edgeNode);

We need to create a node because bodies need to be attached to something. We could do the same with a sprite that was going to act as a border or could just leave it like that and put the art on top of it as it is not going to be movable.

I am using a couple macros:

#define PTM_RATIO 32

#define METER_TO_PIXEL(n) ((n) * PTM_RATIO) //macro to convert meters to pixels.

#define PIXEL_TO_METER(n) ((n) / PTM_RATIO) //macro to convert pixels to meters.

PTM_RATIO defines how many pixels i have per meter and the other two allow me to switch between them, so i can basically work in meters in my game.
My PTM_RATIO is 32 and my DesignResolution is 480x320, so i have an area of 15mx10m.

In this example i am creating the edge at the end of the visible size, but i am using a thickness of 1 meter (in every direction), so as a result i have a border around my screen of 1 meter (+1 more meter in the non visible area). I doubt he can escape now :P

No comments:

Post a Comment