这个是放在update里面的,我的感觉就是在球速过快的时候,在上面图中的情况中由于代码的顺序,会先检测到墙壁然后检测到球拍,然后给球拍加了速,这样就不对了。但不清楚是不是这样的问题。求大佬指点
private void MoveBall()
{
// actually move the ball
m_ball.X += m_ball.DX;
m_ball.Y += m_ball.DY;
// did ball touch top or bottom side?
if (m_ball.Y <= 0 ||
m_ball.Y >= SCREEN_HEIGHT - m_ball.Height)
{
// reverse vertical direction
m_ball.DY *= -1;
}
// did ball touch the left side?
if (m_ball.X <= 0)
{
// at higher speeds, the ball can leave the
// playing field, make sure that doesn't happen
m_ball.X = 0;
// increment player 2's score
m_Score2++;
// reduce speed, reverse direction
m_ball.DX = 5.0f;
}
// did ball touch the right side?
if (m_ball.X >= SCREEN_WIDTH - m_ball.Width)
{
// at higher speeds, the ball can leave the
// playing field, make sure that doesn't happen
m_ball.X = SCREEN_WIDTH - m_ball.Width;
// increment player 1's score
m_Score1++;
// reduce speed, reverse direction
m_ball.DX = -5.0f;
}
// reset game if a player scores 10 goals
if (m_Score1 > 9 || m_Score2 > 9)
{
ResetGame();
}
// did ball hit the paddle from the front?
if (CollisionOccurred())
{
// reverse hoizontal direction
m_ball.DX *= -1;
// increase the speed a little.
m_ball.DX *= 1.15f;
}
}
// check for a collision between the ball and paddles
private bool CollisionOccurred()
{
// assume no collision
bool retval = false;
// heading towards player one
if (m_ball.DX < 0)
{
Rectangle b = m_ball.Rect;
Rectangle p = m_paddle1.Rect;
retval =
b.Left < p.Right &&
b.Right > p.Left &&
b.Top < p.Bottom &&
b.Bottom > p.Top;
}
// heading towards player two
else // m_ball.DX > 0
{
Rectangle b = m_ball.Rect;
Rectangle p = m_paddle2.Rect;
retval =
b.Left < p.Right &&
b.Right > p.Left &&
b.Top < p.Bottom &&
b.Bottom > p.Top;
}
return retval;
}