#ifndef __HELLOWORLD_SCENE_H__ #define __HELLOWORLD_SCENE_H__ #include "cocos2d.h" USING_NS_CC; class HelloWorld : public cocos2d::Layer { public: static cocos2d::Scene* createScene(); virtual bool init(); virtual bool onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event); virtual void onEnter(); virtual void onExit(); CREATE_FUNC(HelloWorld); void addNewSpriteAtPosition(Vec2 p); }; #endif // __HELLOWORLD_SCENE_H__
void HelloWorld::onEnter() { Layer::onEnter(); auto listener = EventListenerPhysicsContact::create(); listener->onContactBegin = [](PhysicsContact& contact) ① { auto spriteA = (Sprite*)contact.getShapeA()->getBody()->getNode(); ② auto spriteB = (Sprite*)contact.getShapeB()->getBody()->getNode(); ③ if (spriteA && spriteA->getTag() == 1 && spriteB && spriteB->getTag() == 1) ④ { spriteA->setColor(Color3B::YELLOW); spriteB->setColor(Color3B::YELLOW); } log("onContactBegin"); return true; }; listener->onContactPreSolve = [] (PhysicsContact& contact, PhysicsContactPreSolve& solve) { ⑤ log("onContactPreSolve"); return true; }; listener->onContactPostSolve = [] (PhysicsContact& contact, const PhysicsContactPostSolve& solve) ⑥ log("onContactPostSolve"); }; listener->onContactSeperate = [](PhysicsContact& contact) { ⑦ auto spriteA = (Sprite*)contact.getShapeA()->getBody()->getNode(); auto spriteB = (Sprite*)contact.getShapeB()->getBody()->getNode(); if (spriteA && spriteA->getTag() == 1 && spriteB && spriteB->getTag() == 1) { spriteA->setColor(Color3B::WHITE); spriteB->setColor(Color3B::WHITE); } log("onContactSeperate"); }; Director::getInstance()->getEventDispatcher()-> addEventListenerWithFixedPriority(listener,1); ⑧ } void HelloWorld::onExit() { Layer::onExit(); log("HelloWorld onExit"); Director::getInstance()->getEventDispatcher()->removeAllEventListeners(); ⑨ }
bool HelloWorld::onTouchBegan(Touch* touch, Event* event) { Vec2 location = touch->getLocation(); addNewSpriteAtPosition(location); return false; } void HelloWorld::addNewSpriteAtPosition(Vec2 p) { auto sp = Sprite::create("BoxA2.png"); sp->setTag(1); auto body = PhysicsBody::createBox(sp->getContentSize()); body->setContactTestBitmask(0xFFFFFFFF); ① sp->setPhysicsBody(body); sp->setPosition(p); this->addChild(sp); }
body1->setCategoryBitmask(0x01); //0001 body1->setCollisionBitmask(0x03); //0011 body2->setCategoryBitmask(0x02); //0010 body2->setCollisionBitmask(0x01); //0001 body3->setCategoryBitmask(0x04); //0100 body3->setCollisionBitmask(0x06); //0110
body1和 body1之间、body1和 body2、body3和 body3能够互相发生碰撞反应,body1和body3不能发生碰撞反应。box 2不能对box3的碰撞发生反应,但box 3能够对box2的碰撞发生反应。
欢迎关注智捷iOS课堂微信公共平台
原文地址:http://blog.csdn.net/tonny_guan/article/details/39584055