在cocos2dx开发时我们会遇到cocos2dx碰撞检测,那么cocos2dx碰撞检测是怎样实现的呢?现在我们就来看具体的实现过程。
在此场景中,我们假设有很多敌人和子弹,其中子弹可以击中敌人,并且碰撞后子弹和敌人都会随之消失。
首先,我们需要去追踪这些敌人和子弹。我们可以为这两种物体添加tag,在这里我们给敌人添加tag=1,给子弹添加tag=2,。因为CCSprite继承自CCNode,因为已经有了setTag和getTag方法;我们可以通过这种方式来区分不同的精灵。
添加两个成员对象在HelloWorldScene.h中。用来分别存储存在的敌人和子弹。
- [cpp] view plaincopy
- protected:
- cocos2d::CCArray *_targets;
- cocos2d::CCArray *_projectiles;
- [cpp] view plaincopy
- // 初始化
- _targets = new CCArray;
- _projectiles = new CCArray;
- HelloWorld::~HelloWorld()
- {
- if (_targets)
- {
- _targets->release();
- _targets = NULL;
- }
- if (_projectiles)
- {
- _projectiles->release();
- _projectiles = NULL;
- }
- // cpp不需要调用super释放,虚析构函数将会做这些事
- }
- HelloWorld::HelloWorld()
- :_targets(NULL)
- ,_projectiles(NULL)
- {
- }
- [cpp] view plaincopy
- // 添加到数组中
- target->setTag(1);
- _targets->addObject(target);
- [cpp] view plaincopy
- // 添加到_projectiles数组中
- projectile->setTag(2);
- _projectiles->addObject(projectile);
- [cpp] view plaincopy
- void HelloWorld::spriteMoveFinished(CCNode* sender)
- {
- CCSprite *sprite = (CCSprite *)sender;
- this->removeChild(sprite, true);
- if (sprite->getTag() == 1) // target
- {
- _targets->removeObject(sprite);
- }
- else if (sprite->getTag() == 2) // projectile
- {
- _projectiles->removeObject(sprite);
- }
- }
在HelloWorldScene.h中声明它,在HelloWorldScene.cpp.定义它。
- [cpp] view plaincopy
- void HelloWorld::update(float dt)
- {
- CCArray *projectilesToDelete = new CCArray;
- CCArray* targetsToDelete =new CCArray;
- CCObject* it = NULL;
- CCObject* jt = NULL;
- CCARRAY_FOREACH(_bullet, it)
- {
- CCSprite *projectile = dynamic_cast<CCSprite*>(it);
- CCRect projectileRect = CCRectMake(
- projectile->getPosition().x - (projectile->getContentSize().width/2),
- projectile->getPosition().y - (projectile->getContentSize().height/2),
- projectile->getContentSize().width,
- projectile->getContentSize().height);
- CCARRAY_FOREACH(_target, jt)
- {
- CCSprite *target = dynamic_cast<CCSprite*>(jt);
- CCRect targetRect = CCRectMake(
- target->getPosition().x - (target->getContentSize().width/2),
- target->getPosition().y - (target->getContentSize().height/2),
- target->getContentSize().width,
- target->getContentSize().height);
- if (projectileRect.intersectsRect(targetRect))
- {
- targetsToDelete->addObject(target);
- projectilesToDelete->addObject(projectile);
- }
- }
- }
- CCARRAY_FOREACH(targetsToDelete, jt)
- {
- CCSprite *target = dynamic_cast<CCSprite*>(jt);
- _target->removeObject(target);
- this->removeChild(target, true);
- }
- CCARRAY_FOREACH(projectilesToDelete, it)
- {
- CCSprite* projectile = dynamic_cast<CCSprite*>(it);
- _bullet->removeObject(projectile);
- this->removeChild(projectile, true);
- }
- projectilesToDelete->release();
- targetsToDelete->release();
- [cpp] view plaincopy
- void HelloWorld::onEnter()
- {
- CCLayer::onEnter();
- this->schedule( schedule_selector(HelloWorld::update) );
- }