1

I can get either the paddle following the cursor, or the ball bouncing, but not both at the same time. I've succeeded in making the ball bounce code loop within the while loop, by enclosing it in an infinite while loop, but of course this stops any movement of the paddle.

This code allows the paddle to move normally, but the ball gets stuck on the right side of the window, and bounces 2 pixels left, 2 pixels right (as the velocity is changing back and forth, stuck in the if statement). There's probably an obvious way to loop this chunk of code sensibly, but I can't figure it out.

I tried looking up threads, but got somewhat lost and figured there must be a better way. I am totally stumped - please help!

while (lives > 0 && bricks > 0)
{
    // mouse event
    GEvent event = getNextEvent(MOUSE_EVENT);
    // heard one?
    if (event != NULL)
    {
        // check for movement
        if (getEventType(event) == MOUSE_MOVED)
        {
            // paddle follows cursos
            double px = getX(event) - 30;
            // stop paddle going out of bounds
            if(px>=MAXPADDLEX)
            {
                px = MAXPADDLEX;
            }
            else if(px<0)
            {
                px = 0;
            }
            double py = POSY;
            setLocation(paddle, px, py);
        }
    }


    // bounce the ball
    double velocity = 2;
    move(ball, velocity, 0);
    pause(10);
    // bounce off right side of window
    if (getX(ball) + getWidth(ball) >= WIDTH)
    {
        velocity = -velocity;            
    }
    // bounce off left side of window
    else if (getX(ball) <= 0)
    {
        velocity = -velocity;
    }


}
1
  • I have written similar code, with velocity outside the loop. Still cannot get both the paddle and the ball to move concurrently.
    – user4753
    Commented Mar 5, 2015 at 18:48

1 Answer 1

2

Solved! Defining the velocity outside of the while loop, instead of inside, has fixed the problem. When it was inside the loop, the velocity was reset to a positive number every time the while loop was run, so the ball could never go backwards.

1
  • You may accept your own answer to mark the question as solved!
    – kzidane
    Commented Oct 19, 2014 at 14:14

You must log in to answer this question.

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