0

In my code for breakout, the ball is unable to bounce up and down, though the same code works in bounce.c for bouncing the ball vertically!

Here's the main part meant for moving the ball:

while (lives > 0 && bricks > 0)
{
    // TODO
    double velocity = -0.5;
    move(ball, 0, velocity);

    // bounce off Y axis's edge of window
    if ((getY(ball) + getHeight(ball)) >= getHeight(window) || getY(ball) <=0)
    {
        velocity *= -1;
    }

    pause (10);
    GEvent event = getNextEvent(MOUSE_EVENT);
    if (event != NULL)
    {
        if (getEventType(event) == MOUSE_MOVED)
        {
            double paddleX = getX(event) - (PADDLE_WIDTH / 2);
            setLocation (paddle, paddleX, HEIGHT - 35);
        }
    }
}

This is only the first baby step I've taken towards this problem, and have failed. I am quite unhappy, please help me find errors!

This code though functions all right in the bounce.c program to bounce the ball between up and down, but when I place this code in the breakout.c file, it doesn't work. The ball just moves up and escapes the field of view and well, disappears...

5
  • Welcome to CS50 stack exchange. You mentioned your code doesn't work as expected, but could you describe what it is doing at the moment? For example, is it only going through the loop once? Or does it seem to just sit and wait for your input? Aug 16, 2014 at 10:51
  • Yes please remove the link, or reduce the amount of code shown there. Please be mindful of the honor code - it's fine for you to show your code, but keep it to the parts relevant to the question. Aug 16, 2014 at 10:53
  • @LukeVanIn , is it fine now, I've removed the link from all the places, added a new section describing the problem. :) Aug 16, 2014 at 11:03
  • Can no one help me ? Aug 16, 2014 at 11:22
  • I have added an answer which should point you in the right direction. Please comment on the answer if further clarification is needed, or if it helps you, please mark it as accepted. Aug 16, 2014 at 11:30

1 Answer 1

5

Converting the code to pseudo code might help to reveal the problem:

loop while lives > 0 and bricks > 0

    set velocity to -0.5

    move the ball in the y axis by the velocity

    if the ball touches the top edge or bottom edge

        reverse the velocity

    handle mouse input

    etc

Note that regardless of what happens to the velocity in a collision, the first line in the loop always sets velocity back to 0.5.

You must log in to answer this question.

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