您的位置:首页 > 编程语言 > C语言/C++

C++游戏开发之碰撞检测算法

2014-06-13 11:36 459 查看
/*检测是否碰撞*/
if(CCRectMake(X-mario->getPathLenght()+1,Y,Widht-2,Height).intersectsRect(mario->getPlayerBoundingBox()))
{
/*上面的函数是检测到已经碰撞后, 下面的逻辑是判断碰撞后人物与物体的位置关系*/
/*物体位置和长宽*/
float x2 = X-mario->getPathLenght();
float y2 = Y;
int h2 = Height;
int w2 = Widht;

/*人物位置和长宽*/
int y1 = mario->getPositionY();
int x1 = mario->getPositionX();
float w1 = mario->getCurrentWidth();
float h1 = mario->getCurrentHeight();

/*如果y坐标不重叠 , y坐标就减去人物y轴的速度*/
if (abs(y1+h1-y2)>1e-4)
{
y1-=mario->verticalVelocity;
}

/*     2
5		------------        6
|           |
|	    |
1		|<span style="white-space:pre">	</span>    |       3
|	    |
------------
8	            4               7

上面数字是物体的方位

人物从哪个方位碰撞到物体
*/
if ((y1>=y2)&&(y1+h1<y2+h2))
{
if (x1<x2)//1
{
/*
正面碰撞1
设置x位置
设置水平速度
*/
mario->setPositionX(x2-w1);
mario->horizontalVelocity = 0;
}
else//3
{
/*
正面碰撞3
设置x位置
设置水平速度
*/
mario->setPositionX(x2+w2);
mario->horizontalVelocity = 0;

}
}
else if ((x1>=x2)&&(x1+w1<x2+w2))
{
if (y1>y2)//2
{
/*
正面碰撞2
设置y位置
设置垂直速度
*/
mario->setPositionY(y2+h2);
if (mario->getIsJumping())
{
mario->setIsJumping(false);
}
mario->setIsOnTheObject(true);
}
else//4
{
/*
正面碰撞4
设置y位置
设置垂直速度
*/
mario->setPositionY(y2-h1);

mario->verticalVelocity = -mario->verticalVelocity;
}
}
else if(x1<=x2&&y1>y2)//5
{
/*
碰撞面5 (同时碰撞 面1 和 面2 )
*/
if (x1+w1-x2>y2+h2-y1)
{
/*
如果碰撞到的2比1多
设置y坐标
设置垂直速度
*/
mario->setPositionY(y2+h2);
if (mario->getIsJumping())
{
mario->setIsJumping(false);
}
mario->setIsOnTheObject(true);
}
else
{
/*
如果碰撞到的2比1少
设置x坐标
设置水平速度
*/
mario->setPositionX(x2-w1);
mario->horizontalVelocity = 0;

}
}
else if (x1>=x2&&y1>y2)//6
{
/*
同理。。。。。。
*/
if (x2+w2-x1>y2+h2-y1)
{
mario->setPositionY(y2+h2);
if (mario->getIsJumping())
{
mario->setIsJumping(false);
}
mario->setIsOnTheObject(true);
}
else
{
mario->setPositionX(x2+w2);
mario->horizontalVelocity = 0;

}
}
else if(x1>=x2&&y1<y2)//7
{
if (x2+w2-x1>y1+h1-y2)
{
mario->setPositionY(y2-h1);

mario->verticalVelocity = -mario->verticalVelocity;

mario->setPositionY(mario->getPositionY()+mario->verticalVelocity);

}
else
{
mario->setPositionX(x2+w2);
mario->horizontalVelocity = 0;

}
}
else if (x1<=x2&&y1<y2)//8
{
if (x1+w1-x2>y1+h1-y2)
{
mario->verticalVelocity = -mario->verticalVelocity;
mario->setPositionY(y2-h1);
mario->setPositionY(mario->getPositionY()+mario->verticalVelocity);

}
else
{
mario->setPositionX(x2-w1);
mario->horizontalVelocity = 0;

}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: