Polygon Collision Detection

Polygon Collision Detection
0

#1

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

	PhysicsBody *body = PhysicsBody::createBox(physicsBox);
	body->setGroup(BUNNY_COLLISION_GROUP);
	body->setCollisionBitmask(BUNNY_BITMASK);
	body->setContactTestBitmask(TRUE);

	sprite->setPhysicsBody(body);

	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 ))
	{
		CCLOG("Collision!");
	}

	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?


#2

Are you using the PolygonSprite class?


#3

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);
            body->addShape(shape);
        }
    }
    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);
sprite->setPhysicsBody(body);

#4

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.

2018-10-09_09-37-51


#5

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