0

My ball bounces off all 4 walls with this code:

// initial ball velocity
double xvelocity = 2.0;
double yvelocity = 2.0;

// keep playing until game over
while (lives > 0 && bricks > 0)
{      
    // basic movement
    move(ball, xvelocity, yvelocity); 

    // bounce off edges
    if (getX(ball) + getWidth(ball) >= getWidth(window) || getX(ball) == 0)
    {
        xvelocity = -xvelocity;
    }
    if (getY(ball) + getWidth(ball) >= getHeight(window) || getY(ball) == 0)
    {
        yvelocity = -yvelocity;
    }

but if I change double xvelocity = 2.0 to double xvelocity = drand48() the ball bounces off the bottom, right and top walls, but not the left. Why?

4
  • I don't see anything in the posted code that would account for it. Have you changed something else, or is there more code that is affecting the ball?
    – Cliff B
    Oct 19 '15 at 2:40
  • No, nothing else is changed, and the only other thing affecting ball is its instantiation. gdb shows that the if condition for X is only met once, when it hits the right wall. When it gets to the left wall, the condition is not executing: it's not picking up that getX(ball) == 0, even when it clearly is equal to zero because I can see it in the window. I wonder...because the random value is, say, something like 0.75869453..., could the x-position "skip over" zero? So at one point x == 0.015684 (say) and then at the next round of the loop it's -0.02345 (say), so it's never exactly zero?
    – andydavies
    Oct 19 '15 at 10:52
  • Yes, that's it. I've changed getX(ball) == 0 to be <= and it works.
    – andydavies
    Oct 19 '15 at 10:57
  • It's always somethng subtle like that.
    – Cliff B
    Oct 19 '15 at 16:57
1

Because the random value is, say, something like 0.75869453..., the x-position "skips over" zero. So at one point x == 0.015684 (say) and then at the next round of the loop it's -0.02345 (say), so it's never exactly zero. It works when I change getX(ball) == 0 to getX(ball) <= 0. Amazing how you can see a breakthrough after taking a break and coming back to it!

You must log in to answer this question.

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