Something rather strange is taking place while I test my collision detection for the ball hitting the walls. The code below to my eye seems correct to make the ball bounce off of all 4 walls of the window continuously, but it doesn't. The ball immediately hits the right wall, bounces, hits the bottom wall, bounces, and then goes straight through the left one. GDB showed that the code is noticing the ball is out of bounds and recalculates it's velocity, but the ball just keeps going regardless of those changes which is odd because the loop does then rerun to issue the move function. I did try changing both the way it checked for being out of bounds, and even tried hard coding a distinct negative integer for a new velocity, neither of which worked.
// initial velocity
int xvelocity = drand48() + 3;
int yvelocity = drand48() + 3;
// keep playing until game over
while (lives > 0 && bricks > 0)
{
// did mouse do something?
GEvent event = getNextEvent(MOUSE_EVENT);
// if it did
if (event != NULL)
{
// was it movement?
if (getEventType(event) == MOUSE_MOVED)
{
// make paddle follows cursor movement
double x = getX(event) - pwidth / 2;
setLocation(paddle, x, 550);
}
}
// move circle along x-axis and y-axis
move(ball, xvelocity, yvelocity);
// bounce off right edge of window
if (getX(ball) + getWidth(ball) >= getWidth(window))
{
xvelocity = drand48() + 3;
xvelocity = -xvelocity;
}
// bounce off left edge of window
if (getX(ball) <= 0)
{
xvelocity = drand48() + 3;
xvelocity = -xvelocity;
}
// bounce off bottom edge
if (getY(ball) + getHeight(ball) >= getHeight(window))
{
yvelocity = drand48() + 3;
yvelocity = -yvelocity;
}
// bounce off top edge
if (getY(ball) <= 0)
{
yvelocity = drand48() + 3;
yvelocity = -yvelocity;
}
// linger before moving again
pause(10);
}