I've written some code to make the ball bounce off the edges and move diagonally. But the ball just disappears off the edge of the window! I've read elsewhere that I have to initialise the velocity variables outside the while loop, but I've done this and it still happens! The ball instantiates fine, it moves, but it just disappears off the edge instantly! I'm totally confused!
Here is my while loop:
double velocity = drand48();
double velocityY = 2;
// keep playing until game over
while (lives > 0 && bricks > 0)
{
// make paddle respond to mouse movement
GEvent event = getNextEvent(MOUSE_EVENT);
if (event != NULL)
{
if (getEventType(event) == MOUSE_MOVED)
{
double x = getX(event) - getWidth(paddle)/2;
setLocation(paddle, x, 500);
}
}
move (ball, velocity, velocityY);
if (getX(ball) + getWidth(ball) >= getWidth(window))
{
velocity = -velocity;
}
else if (getX(ball) <= 0)
{
velocity = -velocity;
}
else if (getY(ball) <= 0)
{
velocityY = -velocityY;
}
}
#define
d the theRADIUS
of theball
and theWIDTH
of thewindow
as constants, you should use that instead ofgetWidth(ball)
andgetWidth(window)
. Also assigngetX(ball)
andgetY(ball)
to two variables, outside of the if statements, and then use those variables in the if statements. The way you have it you are doing the same thing multiple times. Other that that your code looks good to me. Consider adding the whole code to see if something else is missing.