``````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;

if (m_ball.DX < 0)
{
Rectangle b = m_ball.Rect;
retval =
b.Left < p.Right &&
b.Right > p.Left &&
b.Top < p.Bottom &&
b.Bottom > p.Top;
}
else // m_ball.DX > 0
{
Rectangle b = m_ball.Rect;
retval =
b.Left < p.Right &&
b.Right > p.Left &&
b.Top < p.Bottom &&
b.Bottom > p.Top;
}

return retval;
}
``````

1个回答