制作飞镖忍者(1) Cocos2d-x 3.0alpha0(3)
来源:未知 责任编辑:责任编辑 发表时间:2013-12-06 08:43 点击:次
10.当子弹碰到怪物时,怪物被消灭,子弹消失,即碰撞检测。需要在场景中跟踪目标和子弹,在HelloWorldScene.h声明如下:
Array* _monsters; Array* _projectiles;在构造函数和析构函数,添加如下:
HelloWorld::HelloWorld() { _monsters = NULL; _projectiles = NULL; } HelloWorld::~HelloWorld() { if (_monsters) { CC_SAFE_RELEASE_NULL(_monsters); } if (_projectiles) { CC_SAFE_RELEASE_NULL(_projectiles); } }然后在init函数中初始化这两个数组:
this->_monsters = Array::create(); this->_monsters->retain(); this->_projectiles = Array::create(); this->_projectiles->retain();修改addMonster函数,为怪物精灵添加标签,并加入到数组,代码如下:
_monster->setTag(1); _monsters->addObject(_monster);修改onTouchesEnded函数,为子弹精灵添加标签,并加入到数组,代码如下:
projectile->setTag(2); _projectiles->addObject(projectile);然后修改spriteMoveFinished函数,增加如下代码:
if (sprite->getTag() == 1) { _monsters->removeObject(sprite); } else if (sprite->getTag() == 2) { _projectiles->removeObject(sprite); }添加如下方法:
void HelloWorld::update(float delta) { Array* projectilesToDelete = Array::create(); Object* pObject = NULL; Object* pObject2 = NULL; CCARRAY_FOREACH(_projectiles, pObject) { Sprite* projectile = (Sprite*)pObject; Array* monstersToDelete = Array::create(); CCARRAY_FOREACH(_monsters, pObject2) { Sprite* monster = (Sprite*)pObject2; if (projectile->getBoundingBox().intersectsRect(monster->getBoundingBox())) { monstersToDelete->addObject(monster); } } CCARRAY_FOREACH(monstersToDelete, pObject2) { Sprite* monster = (Sprite*)pObject2; _monsters->removeObject(monster); this->removeChild(monster); } if (monstersToDelete->count() > 0) { projectilesToDelete->addObject(projectile); } monstersToDelete->release(); } CCARRAY_FOREACH(projectilesToDelete, pObject) { Sprite* projectile = (Sprite*)pObject; _projectiles->removeObject(projectile); this->removeChild(projectile); } projectilesToDelete->release(); }遍历子弹数组,计算每一个子弹所可能遇到的怪物,用它们各自的边界框进行交叉检测,检测到交叉,则将怪物对象放入ToDelete(待删除)数组,不能在遍历的时候删除一个对象。若是子弹遇到了怪物,也需要放入ToDelete(待删除)数组。然后从场景和数组中移动掉。同样,也在init函数,安装定时器,代码如下:
相关新闻>>
最新推荐更多>>>
- 发表评论
-
- 最新评论 更多>>