判断两个矩形是否相交的原理详解
bool Rect::intersectsRect(const Rect& rect) const
{
return !( getMaxX() < rect.getMinX() ||
rect.getMaxX() < getMinX() ||
getMaxY() < rect.getMinY() ||
rect.getMaxY() < getMinY());
}
上面这几行代码很简单就是判断相交的反面,就是不想交的情况、
前两行如果其中一个矩形的最左端的x坐标比另外一个矩形的最右端还要大那么这两个矩形一定不想交
后面两行就是判断,其中的一个矩形的最下端y的坐标如果大于了另外一个矩形的最上端那么这两个矩形也一定是不想交的。
当然如果要是从正面来写的话就会很费力,下面是赛车当中的一段代码,大家可以看看写的比较麻烦,但是功能上都是实现了两个矩形碰撞的判断
//主车在敌车的右侧并主车的在敌车的上侧有相同的部分说明是相撞了,直接让主角死亡。(右上)
//if( mainRole->getPosition().x > roles[j]->getPosition().x
//&&mainRole->getPosition().x
//&&mainRole->getPosition().y>roles[j]->getPosition().y
//&&mainRole->getPosition().y
//){
//gameState=CCLabelTTF::create(“Game Over”,”Arial”,96);
//gameState->setPosition(Point(visibleSize.width/2,visibleSize.height/2-200));this->addChild(gameState);
//isPlaying=false;
//pStart->setVisible(true);
//CocosDenshion::getInstance()->playEffect(“boom.mp3”);
//marks=0;
//}
//
// //主角的位置在敌车的左侧且位于敌车的上侧(左上)
// else if(mainRole->getPosition().x+mainRole->getContentSize().width>roles[j]->getPosition().x
//&&mainRole->getPosition().x+mainRole->getContentSize().width
//&&mainRole->getPosition().y>roles[j]->getPosition().y
//&&mainRole->getPosition().y
//){;
//gameState=CCLabelTTF::create(“Game Over”,”Arial”,96);
//gameState->setPosition(Point(visibleSize.width/2,visibleSize.height/2-200));this->addChild(gameState);
//isPlaying=false;
//pStart->setVisible(true);
//CocosDenshion::getInstance()->playEffect(“boom.mp3”);
//marks=0;
//}
// //(主车在左下)
// else if(mainRole->getPosition().x+mainRole->getContentSize().width>roles[j]->getPosition().x
//&&mainRole->getPosition().x+mainRole->getContentSize().width
//&&mainRole->getPosition().y+mainRole->getContentSize().height>roles[j]->getPosition().y
//&&mainRole->getPosition().y+mainRole->getContentSize().height
//){
//gameState=CCLabelTTF::create(“Game Over”,”Arial”,96);
//gameState->setPosition(Point(visibleSize.width/2,visibleSize.height/2-200));this->addChild(gameState);
//isPlaying=false;
//pStart->setVisible(true);
//marks=0;
//CocosDenshion::getInstance()->playEffect(“boom.mp3”);
//}
// //(主车在敌车的右下)
// else if(mainRole->getPosition().x > roles[j]->getPosition().x
//&&mainRole->getPosition().x < roles[j]->getPosition().x+roles[j]->getContentSize().width
//&&mainRole->getPosition().y+mainRole->getContentSize().height>roles[j]->getPosition().y
//&&mainRole->getPosition().y+mainRole->getContentSize().height
//){
//gameState=CCLabelTTF::create(“Game Over”,”Arial”,96);
//gameState->setPosition(Point(visibleSize.width/2,visibleSize.height/2-200));
//this->addChild(gameState);
//isPlaying=false;
//pStart->setVisible(true);
//CocosDenshion::getInstance()->playEffect(“boom.mp3”);
//marks=0;
//}
还没有评论,来说两句吧...