Hi,
After reading this post and this about collision detecting in cocos2dx, i decided to run a few test.
In my game there are player, player’s weapon and enemy. Enemy chase player. Weapon will be shoot from player’s position so Player-Weapon no collide, Player-Enemy collide and Weapon-Enemy collide.
#define PLAYER_CATEGORY_BITMASK 0x000001
#define PLAYER_COLLISION_BITMASK 0x000004
#define WEAPON_CATEGORY_BITMASK 0x000002
#define WEAPON_COLLISION_BITMASK 0x000004
#define ENEMY_CATEGORY_BITMASK 0x000004
#define ENEMY_COLLISION_BITMASK 0x000003
Then i create physic body for the sprites:
auto playerBody = PhysicsBody::createBox(_player->getContentSize());
playerBody->setCategoryBitmask(PLAYER_CATEGORY_BITMASK);
playerBody->setCollisionBitmask(PLAYER_COLLISION_BITMASK);
playerBody->setContactTestBitmask(true);
playerBody->setDynamic(true);
playerSprite->setPhysicsBody(playerBody);
auto weaponBody = PhysicsBody::createBox(_playerWeapon->getContentSize());
weaponBody->setDynamic(true);
weaponBody->setCategoryBitmask(WEAPON_CATEGORY_BITMASK);
weaponBody->setCollisionBitmask(WEAPON_COLLISION_BITMASK);
weaponBody->setContactTestBitmask(true);
weaponBody->setAngularVelocity(20);//the weapon will be spinning around
weaponSprite->setPhysicsBody(weaponBody);
auto enemyBody = PhysicsBody::createBox(_enemy->getContentSize());
enemyBody->setCategoryBitmask(ENEMY_CATEGORY_BITMASK);
enemyBody->setCollisionBitmask(ENEMY_COLLISION_BITMASK);
enemyBody->setContactTestBitmask(true);
enemyBody->setDynamic(true);
enemySprite->setPhysicsBody(enemyBody);
Next is handle contact, in init()
auto contactListener = EventListenerPhysicsContact::create();
contactListener->onContactBegin = CC_CALLBACK_1(Game::onContactBegin, this);
Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(contactListener, this);
Then
bool Game::onContactBegin(cocos2d::PhysicsContact &contact)
{
PhysicsBody *a = contact.getShapeA()->getBody();
PhysicsBody *b = contact.getShapeB()->getBody();
CCLOG(“Contact”);
return true;
}
The result is good on screen, player-weapon no collide (player’s sprite stood still after shoot a weapon), player/weapon-enemy collide but the Event onContactBegin()
is not called. But if i remove the following lines:
playerBody->setCategoryBitmask(PLAYER_CATEGORY_BITMASK);
weaponBody->setCategoryBitmask(WEAPON_CATEGORY_BITMASK);
enemyBody->setCategoryBitmask(ENEMY_CATEGORY_BITMASK);
Then the event onContactBegin()
is called when there is contact, but now player-weapon collide each other (player’s sprite get recoil from shoot the weapon). What is the different with/without categortyBitmask
and if i continue with no categortyBitmask
how to make Player-Weapon not collide. Thanks.