目标:当一颗子弹击中目标时会产生一个圆形范围的爆炸,当有敌人在这个范围内时都会产生伤害,而伤害值依据圆形的圆心与敌人的中心的距离来判断伤害高低。
void Quantum::quantumExplosion(float detla) {
CCArray* enemies = Container::sharedContainer()->getEnemies();
CCObject* iterator;
CCPoint quantumPos = _quantumCollision->getPosition();
float enemyMinX = 0;
float enemyMaxX = 0;
float enemyMinY = 0;
float enemyMaxY = 0;
CCARRAY_FOREACH(enemies, iterator) {//遍历敌机
Enemy* enemy = (Enemy*)iterator;
if(enemy->getActive()) {//敌机除于激活状态
CCRect enemyRect = enemy->boundingBox();
enemyMinX = enemyRect.getMinX();
enemyMaxX = enemyRect.getMaxX();
enemyMinY = enemyRect.getMinY();
enemyMaxY = enemyRect.getMaxY();
bool isCollision = false;
float distance = 0;
CCPoint p;
//如果敌机的坐标矩形在圆心的第一象限或第二象限或第三象限或第四象限时,只要矩形的四个坐标点与圆心的距离小于爆炸半径即可判断敌机是在爆炸范围内的
//若果敌机的坐标矩形横跨两个象限,则把圆形包裹成一个矩形,判断敌机的矩形与这个矩形是否有碰撞即可判断敌机是在爆炸范围内的
if(enemyMinX > quantumPos.x && enemyMinY > quantumPos.y) {//第一象限
p = CCPointMake(enemyMinX, enemyMinY);
distance = ccpDistance(quantumPos, p);
if(distance < this->_explosiveRange) {
isCollision = true;
}
}else if(enemyMaxX < quantumPos.x && enemyMinY > quantumPos.y) {//第二象限
p = CCPointMake(enemyMaxX, enemyMinY);
distance = ccpDistance(quantumPos, p);
if(distance < this->_explosiveRange) {
isCollision = true;
}
}else if(enemyMaxX < quantumPos.x && enemyMinY < quantumPos.y) {//第三象限
p = CCPointMake(enemyMaxX, enemyMaxY);
distance = ccpDistance(quantumPos, p);
if(distance < this->_explosiveRange) {
isCollision = true;
}
}else if(enemyMinX > quantumPos.x && enemyMinY < quantumPos.y) {//第四象限
p = CCPointMake(enemyMinX, enemyMaxY);
distance = ccpDistance(quantumPos, p);
if(distance < this->_explosiveRange) {
isCollision = true;
}
}else {//矩形碰撞
CCRect rect = CCRectMake(quantumPos.x - this->_explosiveRange, quantumPos.y - this->_explosiveRange, this->_explosiveRange * 2, this->_explosiveRange * 2);
isCollision = rect.intersectsRect(enemyRect);
if(isCollision) {//
float d1 = abs(enemyMinX - quantumPos.x);
float d2 = abs(enemyMaxX - quantumPos.x);
float d3 = abs(enemyMinY - quantumPos.y);
float d4 = abs(enemyMaxY - quantumPos.y);
float d[4] = {d1, d2, d3, d4};
distance = this->minDistance(d, 4);//计算最短距离
}
}
if(isCollision) {//根据距离计算伤害值,距离越远,伤害越小
float realDemage = 1 / distance * this->_demage;
enemy->hurt(realDemage);
}
}
}
}