I'm working on breakout, and trying to set my initial x and y velocities. My goal is to keep the speed constant while changing the direction. To do this, I'm trying to send the y velocity equal to the square root of ( (constant)^2 - (x velocity)^2 ). I tried using this formula:

// initial velocities
double velocityx = drand48() + 3;
double velocityy = sqrt(pow(2, 2) - pow(velocityx, 2));

It compiles, but I get a "segmentation fault (core dumped)" error upon running. I was thinking it may have to do with squaring a double?

Any ideas? Thank you!

  • Not clear about what you're asking. Are you setting your initial velocity of the ball when starting a second or later ball, (or the first one), or are you asking how to maintain velocity while changing direction when it hits an object? – Cliff B Mar 28 '15 at 23:00

The statement double velocityy = sqrt(pow(2, 2) - pow(velocityx, 2)); is the reason for the fault. Since velocityx will always be 3 or more, pow(velocityx, 2) will always be larger than pow(2,2), which is 4. The importance of this is that sqrt() is always operating on a negative number. MAN says that sqrt( a negative number) will return NAN, or not a number. Since your code isn't posted, I'm guessing that whatever tries to use velocity next is throwing the error.

You could try sqrt(fabs(....)) to get the value, and write additional code to determine the sign to be applied, or just hard code it if the direction- the sign of the variable - is always the same. fabs is the absolute value function for floats.

However, I'm confused about the overall logic. It looks like you're basing your calculation on x squared + y squared = z squared. In this, z squared is always going to be the largest of the three (z squared = 4, so z =2). Yet, your velocityx is always greater than 3. Is there something that needs to be altered?

  • Thank you, Cliff! Yes I didn't factor in that 'z' needs to be greater than 'velocityx', that explains it. – Annie Fogel Mar 29 '15 at 22:40

You must log in to answer this question.

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