# why does drand48 alter my collision detection for bouncing?

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?

• 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? 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? Oct 19 '15 at 10:52
• Yes, that's it. I've changed `getX(ball) == 0` to be `<=` and it works. Oct 19 '15 at 10:57
• It's always somethng subtle like that. Oct 19 '15 at 16:57

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!