0

I'm working through pset3 and noticed that when I declare my ball's velocities outside the while loop, my collisions against the wall's edges work, i.e. the ball bounces away, but when the velocities are declared within the while loop, my ball just floats right past the end of the window. Can anyone help me understand why this is the case since I think I'm getting confused with variable scope here..

// velocities declared outside while loop   
//ball bounces as expected


int main (void)
{....


    double x_velocity = drand48();
    double y_velocity = 0.2;

    while (lives > 0 && bricks > 0)
    {
         GEvent event = getNextEvent(MOUSE_EVENT);
         ....

         move(ball, x_velocity, y_velocity);

         if(getX(ball) + (2*RADIUS) >= WIDTH)
         {
             x_velocity = -x_velocity;
         }

vs

// velocities declared in while loop    
//ball goes past window's edge      



int main (void)
{....

    while (lives > 0 && bricks > 0)
    {
         GEvent event = getNextEvent(MOUSE_EVENT);
         ....

         double x_velocity = drand48();
         double y_velocity = 0.2;
         move(ball, x_velocity, y_velocity);

         if(getX(ball) + (2*RADIUS) >= WIDTH)
         {
             x_velocity = -x_velocity;
         }
2

You're on the right track, but there's an additional issue going on.

Think of scope this way: a variable only exists within the curly braces that immediately surround it. So, when you declare them outside of the while loop, the variables exist and persist inside of all of main. When you declare them inside the while loop's curly braces, they only exist inside the while loop.

However, the real issue is that you not only declare them, but you also initialize them at the start of the loop. That means that it doesn't matter what happened to them on the previous pass, or what you may have done to them. As soon as the loop hits the declaration statements, they're reinitialized again, so the ball just keeps going. It probably changes speed and angle because of the random function, but will still continue in the same general direction.

If this answers your question, please click on the check to accept. Let's keep up on forum housekeeping. ;-)

| improve this answer | |
1

Whoops, sorry guys. Just realized that for the latter situation, when the code goes through the If statement then loops back to the top of the while statement, the velocities get assigned back to their original values, i.e. they won't go negative, while for the former situation allows the velocity to go negative.

| improve this answer | |

You must log in to answer this question.

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