Polygon Collision Detection

Polygon Collision Detection


I am able to detect collisions when I create a physics body as a box:

	PhysicsBody *body = PhysicsBody::createBox(physicsBox);


	scene->addChild(sprite, 1);

And using this event listener:

auto eventContactListener = EventListenerPhysicsContact::create();
eventContactListener->onContactBegin = CC_CALLBACK_1(GameScene::onContactBegin, this);
this->_eventDispatcher->addEventListenerWithSceneGraphPriority(eventContactListener, this);

and this function to detect the collisions:

bool GameScene::onContactBegin(PhysicsContact &contact)
	PhysicsBody *a = contact.getShapeA()->getBody();
	PhysicsBody *b = contact.getShapeB()->getBody();

	if ((a->getCollisionBitmask() == BITMASK_1 && b->getCollisionBitmask() == BITMASK_2 ) ||
		(a->getCollisionBitmask() == BITMASK_2 && b->getCollisionBitmask() == BITMASK_1 ))

	return true;

However, I have started creating physics bodies using polygons and although I am adding the sprites to the same scene as before, the onContactBegin function shown above is no longer detecting collisions.

It is important to note that in the game, the bodies are interacting with each other as they should, I am just not able to detect those collisions in the code.

Is there something different I need to do when detecting physics polygon body collisions?


Are you using the PolygonSprite class?


I am actually using PhysicsEditor and its loader code is below:

PhysicsBody *PhysicsShapeCache::createBodyWithName(const std::string &name)
    BodyDef *bd = getBodyDef(name);
    PhysicsBody *body = PhysicsBody::create();
    setBodyProperties(body, bd);

    for (auto fd : bd->fixtures)
        PhysicsMaterial material(fd->density, fd->restitution, fd->friction);
        for (auto polygon : fd->polygons)
            auto shape = PhysicsShapePolygon::create(polygon->vertices, polygon->numVertices, material, fd->center);
            setShapeProperties(shape, fd);
    return body;

It appears as though it is creating several polygon shapes and then adding each one in succession to the body.

This code is called just before the function createBodyWithName():

PhysicsBody *body = createBodyWithName(name);


This is most likely an issue with the collision bits set in PhysicsEditor.

You have to set the bits for Category, Collision and Contact for each fixture. See screenshot.



That did the trick! Thank you so much.

The ‘Contact’ column was staring me right in the face the whole time but I never thought to check it. I checked the Category and Collision boxes though… facepalm