我正在使用精灵制作简单的DirectX 9 2d游戏。我已经编写了(并将我在书籍和在线上找到的一些代码片段拼凑在一起)一个小型引擎,现在应用于应用程序的碰撞检测元素。我在为碰撞检测创建的函数中收到堆栈溢出错误:
UINT Game::IsCollision(int a, int b)
{
if(a != b)
{
if((m_Sprites[a].posrect.bottom >= m_Sprites[b].posrect.top) && (m_Sprites[a].posrect.top <= m_Sprites[b].posrect.bottom) && (m_Sprites[a].posrect.right >= m_Sprites[b].posrect.left) && (m_Sprites[a].posrect.left <= m_Sprites[b].posrect.right))
{
if(m_Sprites[a].posrect.top < m_Sprites[b].posrect.top && m_Sprites[a].posrect.top < m_Sprites[b].posrect.bottom && m_Sprites[a].posrect.bottom < m_Sprites[b].posrect.bottom)
{
return BOTTOM;
}
else if(m_Sprites[b].posrect.top < m_Sprites[a].posrect.top && m_Sprites[a].posrect.top < m_Sprites[b].posrect.bottom && m_Sprites[b].posrect.bottom < m_Sprites[a].posrect.bottom)
{
return TOP;
}
else if( m_Sprites[a].posrect.left < m_Sprites[b].posrect.left && m_Sprites[b].posrect.left < m_Sprites[a].posrect.right && m_Sprites[a].posrect.right < m_Sprites[b].posrect.right)
{
return RIGHT;
}
else if( m_Sprites[b].posrect.left < m_Sprites[a].posrect.left && m_Sprites[a].posrect.left < m_Sprites[b].posrect.right && m_Sprites[b].posrect.right < m_Sprites[a].posrect.right)
{
return LEFT;
}
}
else
{
return NOCOLLISION;
}
}
return NOCOLLISION;
}
这也是我如何调用函数:
void Game::UpdateSprite(int e)
{
UINT collision;
for(int f = 0; f < MAX_SPRITES; f++)
{
if(m_Sprites[f].occupied && m_Sprites[e].occupied && f != e)
{
collision = IsCollision(f, e);
switch (collision)
{
case BOTTOM:
m_Sprites[e].movey *= -1;
m_Sprites[f].movey *= -1;
break;
case TOP:
m_Sprites[e].movey *= -1;
m_Sprites[f].movey *= -1;
break;
case RIGHT:
m_Sprites[e].movex *= -1;
m_Sprites[f].movex *= -1;
break;
case LEFT:
m_Sprites[e].movex *= -1;
m_Sprites[f].movex *= -1;
break;
case NOCOLLISION:
break;
}
UpdateSprite(e);
UpdateSprite(f);
}
}
}
答案 0 :(得分:3)
从UpdateSprite底部删除对UpdateSprite的调用。当函数调用自身而没有递归的终止案例时,您将获得无限递归和堆栈溢出。