0

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;
    }   
}
1
  • If you have #defined the the RADIUS of the ball and the WIDTH of the window as constants, you should use that instead of getWidth(ball) and getWidth(window). Also assign getX(ball) and getY(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.
    – ChrisG
    Aug 1 '15 at 9:32
0

I see your ball heading mostly down and off the window. You never test for down. Which ultimately is what you will need to detect the ball getting past the paddle. Remember that zero y for the window is at the top, and positive velocities well make the ball travel down and to the right. If you don't seed the random number gen then it will always do the same thing. For testing make velocity an hard number like 3 to see the ball go right and left.

This site is temporarily in read only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .