Cocos2d-x collision
Collision detection
Basic idea is same as Sprite Kit of iOS Collision in SpriteKit
Set physics world
Header
class GameScene : public cocos2d::Layer
{
public:
// Phisics
void setPhysicsWorld(cocos2d::PhysicsWorld* world) {
mWorld = world;
mWorld->setGravity(cocos2d::Vect(0,0)); // No gravity
}
bool onContactBegin(cocos2d::PhysicsContact& contact);
cocos2d::PhysicsWorld* mWorld;
}
To enable physics, you need to change crateScene a bit.
Scene* GameScene::createScene()
{
// 'scene' is an autorelease object
//auto scene = Scene::create();
auto scene = Scene::createWithPhysics(); // For physics
// 'layer' is an autorelease object
auto layer = GameScene::create();
layer->setPhysicsWorld(scene->getPhysicsWorld());
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
Apply physics in sprite and other objects.
Basically, create physics area and apply it to an object.
Register listener
// For Physics auto contactListener = EventListenerPhysicsContact::create(); contactListener->onContactBegin = CC_CALLBACK_1(GameScreen::onContactBegin, this); this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(contactListener, this);
These should be in init method
Create physics and apply
auto body = PhysicsBody::createCircle(playerSprite->getContentSize().width /2); // radius body->setContactTestBitmask(true); body->setDynamic(true); playerSprite->setPhysicsBody(body);
onContactBegin
To handle collision in method, you need to implement onContactBegin
bool GameScene::onContactBegin(cocos2d::PhysicsContact& contact) {
// Do something
auto spriteA = (Sprite*)contact.getShapeA()->getBody()->getNode();
auto spriteB = (Sprite*)contact.getShapeB()->getBody()->getNode();
if (spriteA->getName().compare("A") == 0 && spriteB->getName().compare("B") == 0) {
}
return true;
}
Tips
Ignore actual collision
Go through
node->setDynamic(false);
