bool BaseTower::isIntersect() { GameManager * instance = GameManager::getInstance(); bool isIntersect = false; //和炮塔比较 for (int i = 0; i < instance->towerVector.size(); i++) { auto tempTower = instance->towerVector.at(i); if (tempTower != this) //不能和自己比较,我勒个去,想了半天,因为自己这个炮塔也在vector中 { auto towerMapPos = instance->map->convertToNodeSpaceAR(this->getPosition()); //log("towerMapPos %f %f", towerMapPos.x, towerMapPos.y); auto towerRect = Rect{ towerMapPos.x, towerMapPos.y, this->towerSprite->getBoundingBox().size.width, this->towerSprite->getBoundingBox().size.height }; //log("rect size : %f %f", this->towerSprite->getBoundingBox().size.width, this->towerSprite->getBoundingBox().size.height); //log("tempTowerPos %f %f", tempTower->getPosition().x, tempTower->getPosition().y); auto tempTowerRect = Rect{ tempTower->getPosition().x, tempTower->getPosition().y, tempTower->towerSprite->getBoundingBox().size.width, tempTower->towerSprite->getBoundingBox().size.height }; if (tempTowerRect.intersectsRect(towerRect)) { //log("true"); isIntersect = true; break; } } } //和士兵比较 for (int i = 0; i < instance->soldierVector.size(); i++) { auto tempSoldier = instance->soldierVector.at(i); auto towerMapPos = instance->map->convertToNodeSpaceAR(this->getPosition()); //log("towerMapPos %f %f", towerMapPos.x, towerMapPos.y); auto towerRect = Rect{ towerMapPos.x, towerMapPos.y, this->towerSprite->getBoundingBox().size.width, this->towerSprite->getBoundingBox().size.height }; //log("rect size : %f %f", this->towerSprite->getBoundingBox().size.width, this->towerSprite->getBoundingBox().size.height); //log("tempTowerPos %f %f", tempTower->getPosition().x, tempTower->getPosition().y); auto tempTowerRect = Rect{ tempSoldier->getPosition().x, tempSoldier->getPosition().y, tempSoldier->soldierSprite->getBoundingBox().size.width, tempSoldier->soldierSprite->getBoundingBox().size.height }; if (tempTowerRect.intersectsRect(towerRect)) { //log("true"); isIntersect = true; break; } } return isIntersect; }
void Card::onTouchEnded(cocos2d::Touch* touch, cocos2d::Event* event) { CCLOG("%s : %s(%d:%d)", "Card", "onTouchEnded", this->type, this->number); // ラインとのあたり判定 HelloWorld* world = dynamic_cast<HelloWorld*>(this->getParent()->getParent()); cocos2d::Vector<CardLine*> ite; ite.pushBack(world->line1); ite.pushBack(world->line2); for (CardLine* line : ite) { if (line == this->getLine()) continue; auto box1 = line->getBoundingBox(); auto box2 = this->getBoundingBox(); auto origin = this->getParent()->convertToNodeSpace(box1.origin); // カードとラインが重なっている場合はラインの移動 if (box2.intersectsRect(cocos2d::Rect(origin.x, origin.y, box1.size.width, box1.size.height))) { this->getLine()->removeCard(this); line->putCard(this); this->setGlobalZOrder(0); return; } } this->gobackToStashPosition(); }
bool HelloWorld::CollisionWithFood() { auto foodRect = food->getBoundingBox(); auto headRect = line.front()->getBoundingBox(); return foodRect.intersectsRect(headRect); }
bool Tools::iscollision(Sprite *sprite1, Sprite *sprite2) { auto rect1 = sprite1->boundingBox(); auto rect2 = sprite2->boundingBox(); return rect1.intersectsRect(rect2); }
//Åöײ¼ì²âº¯Êý void BattleField::collisionDetection() { if (bullets.empty() || preys.empty()) { return; } // 1 Vector<Prey*> preyNeedToDelete; Vector<Bullet*> bulletNeedToDelete; // 2 for (int i = 0; i < bullets.size(); i++) { auto bullet1 = bullets.at(i); /*auto bulletRect = Rect(bullet->getPositionX() + bullet->getParent()->getPositionX() - bullet->getContentSize().width / 2, bullet->getPositionY() + bullet->getParent()->getPositionY() - bullet->getContentSize().height / 2, bullet->getContentSize().width, bullet->getContentSize().height);*/ auto bulletRect = bullet1->getBoundingBox(); for (int j = 0; j < preys.size(); j++) { auto enemy = preys.at(j); auto enemyRect = enemy->getBoundingBox(); // 4 if (bulletRect.intersectsRect(enemyRect))// Åöײ³É¹¦ { bullet->setpower(2); auto power = bullet->getpower(); auto hp = enemy->getHp(); hp = hp - 2; enemy->setHp(hp);//¿ÛѪ bulletNeedToDelete.pushBack(bullet1); if(hp<=0) preyNeedToDelete.pushBack(enemy); // 5 break; } } // ÒƳýËÀÁ˵Äprey for (Prey* preytemp:preyNeedToDelete) { preys.eraseObject(preytemp); preytemp->removeFromParentAndCleanup(true); } preyNeedToDelete.clear(); } // ÒƳýËÀÁ˵Äbullet for (const auto& bulletTemp : bulletNeedToDelete) { bullets.eraseObject(bulletTemp); //bulletTemp->removeFromParent(); bulletTemp->removeFromParentAndCleanup(true); } bulletNeedToDelete.clear(); }
void HelloWorld::update(float t) { Vector<Sprite*> targetsToDelete; Vector<Sprite*> projectilesToDelete; for (int i = 0; i < _projectiles.size(); i++) { auto projectile = _projectiles.at(i); auto projectileRect = Rect( projectile->getPositionX() - projectile->getContentSize().width / 2, projectile->getPositionY() - projectile->getContentSize().height / 2, projectile->getContentSize().width, projectile->getContentSize().height ); for (int j = 0; j < _targets.size(); j++) { auto target = _targets.at(j); auto targetRect = Rect( target->getPositionX() - target->getContentSize().width / 2, target->getPositionY() - target->getContentSize().height / 2, target->getContentSize().width, target->getContentSize().height); if (projectileRect.intersectsRect(targetRect)) { targetsToDelete.pushBack(target); } } //C++11 的 range-based for循环 for (Sprite* target : targetsToDelete) { _targets.eraseObject(target); this->removeChild(target); _projectilesDestroyed++; if (_projectilesDestroyed >3) { auto gameOverScene = GameOverScene::create(); gameOverScene->getLayer()->getLabel()->setString("You Win!"); Director::getInstance()->replaceScene(gameOverScene); } } if (targetsToDelete.size() >0) { projectilesToDelete.pushBack(projectile); } targetsToDelete.clear(); } for (const auto& p : projectilesToDelete) { _projectiles.eraseObject(p); this->removeChild(p); //p->removeFromParentAndCleanup(true); } projectilesToDelete.clear(); }
bool HelloWorld::CollisionWithPowerUp() { if (hasPowerUp) { auto powerUpRect = powerUp->getBoundingBox(); auto headRect = line.front()->getBoundingBox(); return powerUpRect.intersectsRect(headRect); } return false; }
static void addTreeToOcclusions(const RenderObject* renderer, const IntRect& frameRect, Vector<IntRect>& occlusions) { if (!renderer) return; if (renderer->isBox() && intersectsRect(renderer, frameRect)) addToOcclusions(toRenderBox(renderer), occlusions); for (RenderObject* child = renderer->slowFirstChild(); child; child = child->nextSibling()) addTreeToOcclusions(child, frameRect, occlusions); }
void PlayerItem::update(float delta) { auto rect = getBoundingBox(); rect.size = Size(TILE_WIDTH,TILE_HEIGHT/2); auto playerRect = GameManager::getInstance()->getPlayer()->getBoundingBox(); if(playerRect.intersectsRect(rect)) { auto manager = GameManager::getInstance(); auto data = PlayerInfoParam::create(); data->setType(getItemType().itemType); switch (data->getType()) { case PlayerInfoParam::kTypeBomb: manager->setBombNum(manager->getBombNum()+1); data->setValue(manager->getBombNum()); Util::playEffect(SOUND_ITEM_GET_BOMB); break; case PlayerInfoParam::kTypeCoin: if(getIdx()==0) { __userDefault->setIntegerForKey(KEY_COIN_NUM, __userDefault->getIntegerForKey(KEY_COIN_NUM)+50); Util::playEffect(SOUND_ITEM_GET_LITTLE_COIN); }else{ __userDefault->setIntegerForKey(KEY_COIN_NUM, __userDefault->getIntegerForKey(KEY_COIN_NUM)+100); Util::playEffect(SOUND_ITEM_GET_BIG_COIN); } data->setValue(__userDefault->getIntegerForKey(KEY_COIN_NUM)); break; case PlayerInfoParam::kTypeShoe: Util::playEffect(SOUND_ITEM_GET_SHOE); manager->setShoe(manager->getShoe()+1); data->setValue(manager->getShoe()); if(_speedUp==false) { manager->setSpeed(manager->getSpeed()*1.3f); manager->getPlayer()->setSpeed(manager->getPlayer()->getSpeed()*1.3f); checkShoeNum(); } break; case PlayerInfoParam::kTypePower: Util::playEffect(SOUND_ITEM_GET_POWER); manager->setBombPower(manager->getBombPower()+1); data->setValue(manager->getBombPower()); break; default: break; } NotificationCenter::getInstance()->postNotification(UPDATE_PLAYER_INFO,data); removeFromParent(); } }
bool testNear(Node * node1 , Node * node2){ auto size1 = node1->getContentSize() * 2; auto pos1 = node1->getPosition(); auto rect1 = Rect(pos1.x - size1.width / 2 , pos1.y - size1.height / 2 , size1.width, size1.height); auto size2 = node2->getContentSize() * 2; auto pos2 = node2->getPosition(); auto rect2 = Rect(pos2.x - size2.width / 2 , pos2.y - size2.height / 2 , size2.width, size2.height); if (rect2.intersectsRect(rect1)) { return true; } return false; }
// Return a set of rectangles that should not be overdrawn by the // plugin ("cutouts"). This helps implement the "iframe shim" // technique of overlaying a windowed plugin with content from the // page. In a nutshell, iframe elements should occlude plugins when // they occur higher in the stacking order. void getPluginOcclusions(Element* element, Widget* parentWidget, const IntRect& frameRect, Vector<IntRect>& occlusions) { RenderObject* pluginNode = element->renderer(); ASSERT(pluginNode); if (!pluginNode->style()) return; Vector<const RenderObject*> pluginZstack; Vector<const RenderObject*> iframeZstack; getObjectStack(pluginNode, &pluginZstack); if (!parentWidget->isFrameView()) return; FrameView* parentFrameView = toFrameView(parentWidget); // Occlusions by iframes. const FrameView::ChildrenWidgetSet* children = parentFrameView->children(); for (FrameView::ChildrenWidgetSet::const_iterator it = children->begin(); it != children->end(); ++it) { // We only care about FrameView's because iframes show up as FrameViews. if (!(*it)->isFrameView()) continue; const FrameView* frameView = toFrameView(it->get()); // Check to make sure we can get both the element and the RenderObject // for this FrameView, if we can't just move on to the next object. // FIXME: Plugin occlusion by remote frames is probably broken. HTMLElement* element = frameView->frame().deprecatedLocalOwner(); if (!element || !element->renderer()) continue; RenderObject* iframeRenderer = element->renderer(); if (isHTMLIFrameElement(*element) && intersectsRect(iframeRenderer, frameRect)) { getObjectStack(iframeRenderer, &iframeZstack); if (iframeIsAbovePlugin(iframeZstack, pluginZstack)) addToOcclusions(toRenderBox(iframeRenderer), occlusions); } } // Occlusions by top layer elements. // FIXME: There's no handling yet for the interaction between top layer and // iframes. For example, a plugin in the top layer will be occluded by an // iframe. And a plugin inside an iframe in the top layer won't be respected // as being in the top layer. const Element* ancestor = topLayerAncestor(element); Document* document = parentFrameView->frame().document(); const WillBeHeapVector<RefPtrWillBeMember<Element> >& elements = document->topLayerElements(); size_t start = ancestor ? elements.find(ancestor) + 1 : 0; for (size_t i = start; i < elements.size(); ++i) addTreeToOcclusions(elements[i]->renderer(), frameRect, occlusions); }
/********************************************************************* ** 功能: 碰撞检测 ** 输入参数: float dt: 延时销毁的时间 ** 返回值: 无 ** 修改记录: *********************************************************************/ void FlightProp::PropCollisionDetective(float dt) { if (NULL == _owner) /* 无施放者死亡或未设置施放者 */ { releaseCallBack(); return; } auto roles = UserData::getInstance()->getRoles(); auto rcA = this->getBoundingBox(); auto ownerInfo = _owner->getRoleInfo(); if (RoleStatus_Death == ownerInfo.status) /* 施放者死亡 */ { releaseCallBack(); return; } bool bHit = false; auto ptLoc = Point(this->getPositionX(), this->getPositionY() - m_fHeight);/* 实际坐标需扣除高度 */ this->setLocalZOrder(_owner->getLocalZOrder()); for(unsigned int index = 0;index < roles.size();index ++) /* 敌人角色遍历获取 */ { auto role = (Role *)roles[index]; auto info = role->getRoleInfo(); if ((RoleStatus_Invincible == info.status) || (RoleStatus_Death == info.status) || (ownerInfo.camp == info.camp) || (_owner->getSceneID() != role->getSceneID())) { continue; /* 无敌、同阵营、死亡或是自身不处理 */ } auto rcB = Rect(role->getPositionX() - 10, role->getPositionY() + 20, 20, 40); /* 有效区域 */ if (true == rcB.intersectsRect(rcA)) /* 碰撞 */ { auto ptOffset = role->getPosition() - ptLoc; if (m_stPropInfo.skillInfo.yAtkDis >= abs(ptOffset.y)) /* 动作有效范围判断 */ { bHit = true; role->roleHurt(_owner, m_stPropInfo.skillInfo, m_bDown); } } } if (true == bHit) { releaseWithDelay(dt); } }
bool HelloWorld::CollisionWithDeath() { auto headRect = line.front()->getBoundingBox(); auto headPos = line.front()->getPosition(); if (headPos.x < 0 || headPos.y < 0 || headPos.x > background->getBoundingBox().getMaxX() || headPos.y > background->getBoundingBox().getMaxY()) { return true; } for (int i = 1; i < line.size() - 1; i++) { auto currRect = line.at(i)->getBoundingBox(); if (headRect.intersectsRect(currRect)) { return true; } } return false; }
bool Scorer::isCollision(){ for(auto &it : _enemies){ if (it->getCurRadius() == _car->getCurRadius() || it->getTrackState() != TrackState::Normal || _car->getTrackState() != TrackState::Normal) { auto rectCar = _car->getBoundingBox(); auto rectEnemy = it->getBoundingBox(); if (rectCar.intersectsRect(rectEnemy)) { _car->blast(); it->blast(); return true; } } } return false; }
Rect Rect::getIntersection( const Rect& r ) const { Rect retVal = Rect::ZERO; if(intersectsRect(r)) { retVal.position.x = std::max(position.x,r.position.x); retVal.position.y = std::max(position.y,r.position.y); retVal.size.width = std::min(position.x + size.width, r.position.x + r.size.width) - retVal.position.x; retVal.size.height = std::min(position.y + size.height, r.position.y + r.size.height) - retVal.position.y; } return retVal; }
void Arrow::removeBullet() { bool isMissed = true; auto instance = GameManager::getInstance(); auto bulletRect = Rect(this->getPositionX() +this->getParent()->getPositionX() - this->getContentSize().width /2, this->getPositionY() +this->getParent()->getPositionY() - this->getContentSize().height/2, this->sprite->getContentSize().width, this->sprite->getContentSize().height ); auto monsterVector = instance->monsterVector; for (int j = 0; j < monsterVector.size(); j++) { auto monster = monsterVector.at(j); auto monsterRect = monster->baseSprite->getBoundingBox(); if (monsterRect.intersectsRect(bulletRect) && monster->getAttackBySoldier()) { auto currHp = monster->getCurrHp(); currHp = currHp - this->getMaxForce() + monster->getArmor(); if(currHp <= 0){ currHp = 0; } monster->setCurrHp( currHp ); monster->getHpBar()->setPercentage((currHp/monster->getMaxHp())*100); monster->getHurt(); isMissed = false; if(currHp == 0){ monster->death(); } break; } } if(isMissed){ sprite->setSpriteFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName("decal_arrow.png")); sprite->runAction(Sequence::create(FadeOut::create(1.0f) ,CallFuncN::create(CC_CALLBACK_0(Bullet::removeFromParent, this)) , NULL)); }else{ this->removeFromParent(); } }
void example00002::update(float delta) { Vector<Sprite*> targetsToDelete; Vector<Sprite*> projectilesToDelete; for (int i =0; i < _projectiles.size(); i++) { auto projectile = _projectiles.at(i); auto projectileRect = Rect( projectile->getPositionX() - projectile->getContentSize().width/2, projectile->getPositionY() - projectile->getContentSize().height/2, projectile->getContentSize().width, projectile->getContentSize().height); for (int j=0; j<_targets.size(); j++) { auto target = _targets.at(j); auto targetRect = Rect( target->getPositionX()-target->getContentSize().width/2, target->getPositionY()-target->getContentSize().height/2, target->getContentSize().width, target->getContentSize().height); if (projectileRect.intersectsRect(targetRect)) { targetsToDelete.pushBack(target); } } for (Sprite* t : targetsToDelete) { _targets.eraseObject(t); this->removeChild(t); } if (targetsToDelete.size() > 0) { projectilesToDelete.pushBack(projectile); } targetsToDelete.clear(); } for (const auto& p:projectilesToDelete ) { _projectiles.eraseObject(p); this -> removeChild(p); } }
bool MapCollideMgr::isHit( MapElement *elem, const cocos2d::Rect &aabb, MapTankVec &tanks ) { MapTankVec::iterator iter = tanks.begin(); for (; iter != tanks.end(); ++iter) { MapTank *tank = *iter; if (elem == tank) { continue; } auto r = tank->getBoundingBox(); if (r.intersectsRect(aabb)) { return true; } } return false; }
bool BattleScene::checkingHero() { bool heroAlive=true; auto activeLayer = this->getCurrentStageLayer(); auto stage = (ObstacleStage *)activeLayer->getChildByTag(activeLayer->getStageNum()); auto boxList = stage->getBoxList(); for (int i=0; i<boxList->size(); i++) { auto box = boxList->at(i); Vec2 worldPoint = (box->getParent())->convertToWorldSpace(box->getPosition()); auto boxRect = Rect(worldPoint.x, worldPoint.y, BOX_SIZE*GAME_SCALE, BOX_SIZE*GAME_SCALE); if (boxRect.intersectsRect(hero->getBoundingBox())) { heroAlive=false; break; } } return heroAlive; }
void HelloWorld::checkCollision(){ auto ypos=bird::getInstance()->getYpos(); if(ypos<=160){ this->changeState(gameEnd::getInstance()); } //!检测小鸟与水管的碰撞 auto rect1=bird::getInstance()->getRect(); rect1.size.height-=5; rect1.size.width-=5; for(auto i=pipes.begin();i!=pipes.end();++i) { auto rect2=(*i)->getBoundingBox(); if(rect1.intersectsRect(rect2)){ changeState(gameEnd::getInstance()); break; } } }
void Main::update(float dt) { dt = dt; for (auto it = _bombs.begin(); it!= _bombs.end();) { Vector<Sprite *> deleteTargets; Sprite *sprite = *it; auto rect1 = Rect( sprite->getPosition().x - (sprite->getContentSize().width/2), sprite->getPosition().y - (sprite->getContentSize().height/2), sprite->getContentSize().width, sprite->getContentSize().height); for (auto it2 = _targets.begin(); it2!= _targets.end(); it2++) { auto *sprite2 = *it2; auto rect2 = Rect( sprite2->getPosition().x - (sprite2->getContentSize().width/2), sprite2->getPosition().y - (sprite2->getContentSize().height/2), sprite2->getContentSize().width, sprite2->getContentSize().height); if (rect1.intersectsRect(rect2)) { deleteTargets.pushBack(sprite2); } } for (auto it3 = deleteTargets.begin(); it3!= deleteTargets.end(); it3++) { _targets.eraseObject(*it3); this->removeChild(*it3, true); } if (deleteTargets.size() > 0) { this->removeChild(*it, true); it = _bombs.erase(it); } else { it++; } } }
void MainScene::intersectsBallAndBlock() { // ブロックの数分回す for( int i = 1; i <= 40; i++ ){ // ブロックのインスタンスを取得 auto block = reinterpret_cast<BlockSprite*>(getChildByTag(i)); if( block != nullptr ){ // ブロックの Rect 取得 auto blocksRect = block->getBoundingBox(); auto ball = (Ball*)getChildByTag(T_Ball); if( ball != nullptr){ // ボールがあれば Rect を作る auto ballRect = ball->getBoundingBox(); // ボールとブロックの衝突判定 if((ballRect.intersectsRect(blocksRect))){ // 乱数でアイテム生成(現状0.3)、ブロックの消去 int random = (int)CCRANDOM_0_1() * 10; if(random < 3){ itemGenerator->generate(block->getPOS()); } block->remove(); // ↓スコアの加算 // ↑スコアの加算 } } } } }
void KeyboardNotificationLayer::keyboardWillShow(IMEKeyboardNotificationInfo& info) { CCLOG("TextInputTest:keyboardWillShowAt(origin:%f,%f, size:%f,%f)", info.end.origin.x, info.end.origin.y, info.end.size.width, info.end.size.height); if (! _trackNode) { return; } auto rectTracked = getRect(_trackNode); CCLOG("TextInputTest:trackingNodeAt(origin:%f,%f, size:%f,%f)", rectTracked.origin.x, rectTracked.origin.y, rectTracked.size.width, rectTracked.size.height); // if the keyboard area doesn't intersect with the tracking node area, nothing need to do. if (! rectTracked.intersectsRect(info.end)) { return; } // assume keyboard at the bottom of screen, calculate the vertical adjustment. float adjustVert = info.end.getMaxY() - rectTracked.getMinY(); CCLOG("TextInputTest:needAdjustVerticalPosition(%f)", adjustVert); // move all the children node of KeyboardNotificationLayer auto children = getChildren(); Node * node = 0; int count = children->count(); Point pos; for (int i = 0; i < count; ++i) { node = (Node*)children->getObjectAtIndex(i); pos = node->getPosition(); pos.y += adjustVert; node->setPosition(pos); } }
void PlayLayer::update(float dt) { GameManager *instance = GameManager::getInstance(); auto bulletVector = instance->bulletVector; auto enemyVector = instance->enemyVector; auto towerVector = instance->towerVector; if(chooseTowerpanle != NULL ) { auto type = chooseTowerpanle->getChooseTowerType(); if( type == TowerType::ARROW_TOWER) { TowerBase* tower = ArrowTower::create(); tower->setPosition(towerPos); this->addChild(tower); instance->towerVector.pushBack(tower); type = TowerType::ANOTHER; chooseTowerpanle->setChooseTowerType(type); } } Vector<EnemyBase*> enemyNeedToDelete; Vector<Sprite*> bulletNeedToDelete; // 碰撞检测 for (int i = 0; i < bulletVector.size(); i++) { auto bullet = bulletVector.at(i); bullet->boundingBox(); auto bulletRect = Rect(bullet->getPositionX()+bullet->getParent()->getPositionX() - bullet->getContentSize().width / 2, bullet->getPositionY() +bullet->getParent()->getPositionY() - bullet->getContentSize().height / 2, bullet->getContentSize().width, bullet->getContentSize().height ); for (int j = 0; j < enemyVector.size(); j++) { auto enemy = enemyVector.at(j); auto enemyRect = enemy->sprite->boundingBox(); if (bulletRect.intersectsRect(enemyRect)) { auto currHp = enemy->getCurrHp(); currHp--; enemy->setCurrHp( currHp ); auto currHpPercentage = enemy->getHpPercentage(); auto offHp = 100 / enemy->getMaxHp(); currHpPercentage -= offHp; if(currHpPercentage < 0){ currHpPercentage = 0; } enemy->setHpPercentage(currHpPercentage); enemy->getHpBar()->setPercentage(currHpPercentage); if(currHp <= 0) { enemyNeedToDelete.pushBack(enemy); } bulletNeedToDelete.pushBack( bullet); } } for (EnemyBase* enemyTemp : enemyNeedToDelete) { enemyTemp->enemyExpload(); instance->enemyVector.eraseObject(enemyTemp); } enemyNeedToDelete.clear(); } for (const auto& bulletTemp : bulletNeedToDelete) { instance->bulletVector.eraseObject(bulletTemp); bulletTemp->removeFromParent(); } bulletNeedToDelete.clear(); }
void GameStart::execute(HelloWorld* s) { //!清除超过屏幕的子弹 auto layer=s->playerlayer; for(auto i=layer->bullets.begin(); i!=layer->bullets.end();) { if((*i)->getPositionY()>810) { (*i)->removeFromParent(); i=layer->bullets.erase(i); } else { i++; } } //!清除超过屏幕的敌机 auto layer1=s->enemylayer; for(auto i=layer1->enemyNum.begin(); i!=layer1->enemyNum.end();) { if((*i)->getPositionY()<-15) { (*i)->removeFromParent(); i=layer1->enemyNum.erase(i); } else { i++; } } //!消灭生命值低于零的死亡敌机 for(auto i=layer1->deadEnemy.begin(); i!=layer1->deadEnemy.end();) { auto life=(int)(*i)->getUserData(); if(life<0) { (*i)->removeFromParent(); i=layer1->deadEnemy.erase(i); } else { i++; } } //!滚动背景图片 s->updateBackGround(); //// layer1->addTime(Director::getInstance()->getDeltaTime()); //!添加敌机 if(layer1->onTime()) { layer1->createEnemy(); layer1->setTime(0); } //!检测炸弹是否启动 auto goodslayer=s->goodslayer; if(goodslayer->getIsEexplosion()) { //!计算所有被消灭的敌机分数 int score1=0; for(auto i=layer1->enemyNum.begin(); i!=layer1->enemyNum.end();) { auto point1=(*i)->getPositionY(); if(point1<800) { int life=(int)(*i)->getUserData(); score1+=life; //!设置死亡敌机消失时间 life=50; (*i)->setUserData((void*)life); (*i)->stopAllActions(); (*i)->getChildByTag(1)->setVisible(true); //!将死亡的敌机放到死亡容器中 layer1->deadEnemy.pushBack(*i); i=layer1->enemyNum.erase(i); } else { i++; } } score1+=s->getScore(); s->setScore(score1); goodslayer->setExplosion(false); } //!添加子弹 layer->update(Director::getInstance()->getDeltaTime()); ///////////////////////////////////////////////////// //////////////////////////////////////////////////// //!碰撞检测 //先判断玩家是否与敌机相撞 auto es=layer1->enemyNum; for(auto i=es.begin(); i!=es.end(); ++i) { auto rect1=(*i)->getBoundingBox(); auto rect2=layer->getPlaneRect(); if(rect1.intersectsRect(rect2)) { //!跳转到游戏结束状态 layer->getPlayer()->getChildByTag(1)->setVisible(true); s->changeState(GameOver::getInstance()); return; } } //!子弹与敌机的碰撞检测 for(auto i=layer1->enemyNum.begin(); i!=layer1->enemyNum.end(); ++i) { for(auto y=layer->bullets.begin(); y!=layer->bullets.end();) { auto rect1=(*i)->getBoundingBox(); auto rect2=(*y)->getBoundingBox(); int life=(int)(*i)->getUserData(); if(rect1.intersectsRect(rect2)) { (*y)->removeFromParent(); y=layer->bullets.erase(y); life--; (*i)->setUserData((void*)life); s->scorePlus(); s->updateScore(); } else { y++; } } } //!将生命值为0的敌机添加到死亡列表里 for(auto i=layer1->enemyNum.begin(); i!=layer1->enemyNum.end();) { int life=(int)(*i)->getUserData(); if(life<=0) { life=50; (*i)->stopAllActions(); (*i)->setUserData((void*)life); (*i)->getChildByTag(1)->setVisible(true); layer1->deadEnemy.pushBack(*i); i=layer1->enemyNum.erase(i); } else { i++; } } //!更新所有死亡的敌机集合 for (auto i=layer1->deadEnemy.begin(); i!=layer1->deadEnemy.end(); ++i) { int life=(int)(*i)->getUserData(); life--; (*i)->setUserData((void*)life); } }
void HelloWorld::update(float dt){ Vector<Monster*> targetsToDelete; Vector<cocos2d::Sprite*> projectilesToDelete; bool monsterHit = false; CCLOG("%s","f**k"); char temp[60]; for (int i=0;i<_projectiles.size();i++) { auto pro = _projectiles.at(i); auto proRect = Rect( pro->getPositionX() - pro->getContentSize().width/2, pro->getPositionY() - pro->getContentSize().height/2, pro->getContentSize().width, pro->getContentSize().height ); for (int j=0;j<_targets.size();j++) { auto target = (Monster*)_targets.at(j); auto targetRect = Rect( target->getPositionX() - target->getContentSize().width/2, target->getPositionY() - target->getContentSize().height/2, target->getContentSize().width, target->getContentSize().height ); if(proRect.intersectsRect(targetRect)){ monsterHit = true; (target->curHp)--; if(target->curHp<=0){ targetsToDelete.pushBack(target); }else { sprintf(temp,"%d",target->curHp); target->hp->setString(temp); } break; // projectilesToDelete.pushBack(pro); } } for (cocos2d::Sprite* sp :targetsToDelete) { this->removeChild(sp,false);//remove以后,因为是true,所以上面的动作也都消除了 _targets.eraseObject(sp); _projectilesDestroyed++; CCLOG("_projectilesDestroyed is %d",_projectilesDestroyed); if (_projectilesDestroyed >3) { LevelManager::sharedInstance()->win(); auto gameOverScene = GameOverScene::create(); //gameOverScene->getLayer()->getLabel()->setString("You Win!"); Director::getInstance()->replaceScene(gameOverScene); } } if (/*projectilesToDelete.size()&&*/monsterHit)//若不删除projectilesToDelete.size(),因为如果projectilesToDelete里此时没有飞镖,就不可能被删除,那么飞镖会一直和马里奥接触,知道curHP变为0 { projectilesToDelete.pushBack(pro); monsterHit =false; //由于没有将monsterhit置为false,后面的飞镖都会删除掉 } targetsToDelete.clear(); } for (auto p : projectilesToDelete) { _projectiles.eraseObject(p); this->removeChild(p); } projectilesToDelete.clear(); CCLOG("%s","shit"); }
MapElemVec MapCollideMgr::getCollideElem( const cocos2d::Rect &aabb, float allowance/* = 0.f*/ ) { int left = (int)floor((aabb.origin.x + allowance) / MAP_ELEM_WIDTH); int right = (int)floor((aabb.origin.x + aabb.size.width - allowance) / MAP_ELEM_WIDTH); int bottom = (int)floor((aabb.origin.y + allowance) / MAP_ELEM_HEIGHT); int top = (int)floor((aabb.origin.y + aabb.size.height - allowance) / MAP_ELEM_HEIGHT); if (left <= 0) { left = 0; } if (bottom <= 0) { bottom = 0; } if (top >= m_map->getRow()) { top = m_map->getRow(); } if (right >= m_map->getCol()) { right = m_map->getCol(); } MapElemVec ret; for (int r = bottom; r <= top; ++r) { for (int c = left; c <= right; ++c) { if (MapElement * elem = m_map->getElementAt(r, c)) { ret.push_back(elem); } } } MapTankVec &userTanks = m_map->getUserTanks(); MapTankVec::iterator iter1 = userTanks.begin(); for (; iter1 != userTanks.end(); ++iter1) { MapTank *tank = *iter1; auto r = tank->getBoundingBox(); if (r.intersectsRect(aabb)) { ret.push_back(tank); } } MapTankVec &enemyTanks = m_map->getEnemyTanks(); MapTankVec::iterator iter2 = enemyTanks.begin(); for (; iter2 != enemyTanks.end(); ++iter2) { MapTank *tank = *iter2; auto r = tank->getBoundingBox(); if (r.intersectsRect(aabb)) { ret.push_back(tank); } } MapBulletVec &bullets = m_map->getBullets(); MapBulletVec::iterator iter3 = bullets.begin(); for (; iter3 != bullets.end(); ++iter3) { MapBullet *bullet = *iter3; auto r = bullet->getBoundingBox(); if (r.intersectsRect(aabb)) { ret.push_back(bullet); } } if (MapElement *base = m_map->getBase()) { auto r = base->getBoundingBox(); if (r.intersectsRect(aabb)) { ret.push_back(base); } } return ret; }
bool HitTestLocation::intersects(const FloatRect& rect) const { return intersectsRect(rect); }
/********************************************************************* ** 功能: 碰撞检测 ** 输入参数: ** 返回值: ** 修改记录: *********************************************************************/ void EnergyBall::PropCollisionDetective() { if (false == m_bCollision) /* 还不到检测时候 */ { return; } if (NULL == _owner) /* 无施放者死亡或未设置施放者 */ { releaseCallBack(); return; } auto ownerInfo = _owner->getRoleInfo(); if (RoleStatus_Death == ownerInfo.status) /* 施放者死亡 */ { releaseCallBack(); return; } auto roles = UserData::getInstance()->getRoles(); if (0 == roles.size()) /* 没有角色(预览模式) */ { releaseCallBack(); return; } if (RoleStatus_Death == m_Role->getRoleInfo().status) /* 选中的角色死亡,另选角色 */ { energyBallSearchObject(); } else { auto ptRole = m_Role->getPosition(); ptRole.y = ptRole.y + m_fHeight; /* 修正目标点为角色身体 */ auto ptOffset = ptRole - this->getPosition(); this->setPosition(this->getPosition() + ptOffset / ptOffset.getLength() * EnergyBallMoveSpeed * 0.4f); } bool bCollision = false; auto rcA = this->getBoundingBox(); auto rcB = Rect(m_Role->getPositionX() - 10, m_Role->getPositionY() + 20, 20, m_fHeight); /* 有效区域 */ if (true == rcB.intersectsRect(rcA)) { bCollision = true; auto info = m_Role->getRoleInfo(); if (ownerInfo.camp == info.camp) /* 对己补给 */ { m_Role->setRoleHpUp(m_stPropInfo.skillInfo.damage); } else /* 对敌伤害 */ { m_Role->roleHurt(_owner, m_stPropInfo.skillInfo, m_bDown); } } if (true == bCollision) { releaseWithDelay(m_fStay); } }