【问题标题】:Collision Detection works but has small glitch?碰撞检测有效但有小故障?
【发布时间】:2013-03-25 14:13:19
【问题描述】:

我写了一个小程序,当它实现时会阻止一个小正方形穿过一个更大的矩形。

当调用collision() 函数时,它会检查形状是否发生碰撞。目前它执行以下操作:

  • 当正方形向形状移动up 时,它不会通过。 (应该这样)
  • 当正方形向down 移动时,它不会通过。 (应该这样)
  • right 移向形状时,它不会通过。 (但它向上移动一个键 按)
  • left 移向形状时,它不会通过。 (但一键向左移动,一键向上移动)(见图)

这是我的collision() 函数:

if     (sprite_Bottom +y_Vel <= plat_Top    ){return false;}
else if(sprite_Top    +y_Vel >= plat_Bottom ){return false;}
else if(sprite_Right  +x_Vel <= plat_Left   ){return false;}
else if(sprite_Left   +x_Vel >= plat_Right  ){return false;}
//If any sides from A aren't touching B
return true;

这是我的move() 函数:

   if(check_collision(sprite,platform1) || check_collision(sprite,platform2)){ //if colliding...
    if     (downKeyPressed ){ y_Vel += speed; downKeyPressed  = false;} //going down
    else if(upKeyPressed   ){ y_Vel -= speed; upKeyPressed    = false;} //going up
    else if(rightKeyPressed){ x_Vel -= speed; rightKeyPressed = false;} //going right
    else if(leftKeyPressed ){ x_Vel += speed; leftKeyPressed  = false;} //going left
   }
   glTranslatef(sprite.x+x_Vel, sprite.y+y_Vel, 0.0); //moves by translating sqaure

我希望 leftright 冲突与 updown 一样工作。我的代码对每个方向都使用相同的逻辑,所以我看不出它为什么这样做......

【问题讨论】:

  • if (sprite_Bottom +y_Vel &lt;= plat_Top ){return false;} 不应该所有这些都是if (sprite_Bottom +y_Vel + speed &lt;= plat_Top ){return false;} 或类似的东西。
  • x_VelglVertex 的位置,speed 是按键移动的量,所以我不这么认为,不。如果你这样做了,广场每次都会在平台内移动得更远。

标签: c++ opengl glut


【解决方案1】:

我认为你应该首先检查你的精灵的角落是否有碰撞。然后,如果您的平台比您的精灵厚,则不需要进一步检查。否则检查精灵的每一面是否与平台发生碰撞。

if ((plat_Bottom <= sprite_Bottom + y_Vel && sprite_Bottom  + y_Vel <= plat_Top)
    && (plat_Left <= sprite_Left + x_Vel && sprite_Left + x_Vel <= plat_Right))
    // then the left-bottom corner of the sprite is in the platform
    return true;

else if ... // do similar checking for other corners of the sprite.
else if ... // check whether each side of your sprite collides with the platform

return false;

【讨论】:

  • 啊,好主意。我没有考虑角落像素。我现在就试试。
  • 还有一些其他可能的问题。例如。如果速度大于行进方向上两个物体的厚度会怎样?
【解决方案2】:

原因似乎是因为您在检查碰撞后将速度与速度相加。

这是一个问题,因为您在碰撞过程中测试的是版本的速度。然后,您将 speed 添加到可能使精灵发生碰撞的速度。如果您要将速度添加到碰撞后 的速度,那么您还需要将速度合并到碰撞算法中。

在你的 collision() 函数中试试这个:

int xDelta = x_Vel + speed;
int yDelta = y_Vel + speed;

if     (sprite_Bottom +yDelta <= plat_Top    ){return false;}
else if(sprite_Top    +yDelta >= plat_Bottom ){return false;}
else if(sprite_Right  +xDelta <= plat_Left   ){return false;}
else if(sprite_Left   +xDelta >= plat_Right  ){return false;}

//If any sides from A aren't touching B
return true;

【讨论】:

  • 这很有道理,我想我明白你在说什么。我刚刚尝试过,但它根本没有碰撞。我一定是错误地执行它。我认为这是因为x_Vel 实际上是vertex 坐标位置,我每次都在更新位置。
  • @Reanimation x_Vel 作为坐标位置让事情有点不同。可能有帮助的是在屏幕上输出一些调试文本,显示精灵的当前xy 位置。然后你可以准确地看到它们碰撞时的样子。这可以帮助您缩小问题范围。
  • @Reanimation 没问题。请告诉我们您的进展情况。
猜你喜欢
  • 1970-01-01
  • 2016-04-24
  • 2015-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-09
  • 1970-01-01
  • 2012-06-19
相关资源
最近更新 更多