NaN - no idea what's going on

So I'm working on a sketch that will make balls bounce off each other.

I'm well aware that for a project like this, vectors are by far the smartest way to go, however, I'm trying to replicate bouncing using x and y velocities.

Here's my current code:

void translateBounce (Ball b1, Ball b2) {
  float b1Xorigin = b1.xVelocity / abs(b1.xVelocity);
  float b2Xorigin = b2.xVelocity / abs(b2.xVelocity);
  float b1Yorigin = b1.yVelocity / abs(b1.yVelocity);
  float b2Yorigin = b2.yVelocity / abs(b2.yVelocity);

  float sharedXVel = fAvg(abs(b1.xVelocity),abs(b2.xVelocity));
  float sharedYVel = fAvg(abs(b1.yVelocity),abs(b2.yVelocity));

  if(b1Xorigin == b2Xorigin) {
    b1.xVelocity = (b1Xorigin*sharedXVel);
    b2.xVelocity = (b2Xorigin*sharedXVel);
  }

  else if(b1Xorigin != b2Xorigin) {
    b1.xVelocity = (b1Xorigin*sharedXVel*(-1.0));
    b2.xVelocity = (b2Xorigin*sharedXVel*(-1.0));
  }

  if(b1Yorigin == b2Yorigin) {
    b1.yVelocity = (b1Yorigin*sharedYVel);
    b2.yVelocity = (b2Yorigin*sharedYVel);
  }

  else if(b1Yorigin != b2Yorigin) {
    b1.yVelocity = (b1Yorigin*sharedYVel*(-1.0));
    b2.yVelocity = (b2Yorigin*sharedYVel*(-1.0));
  }

  b1.wasTranslated = true;
  b2.wasTranslated = true;
}

The basic idea is I figure out if the velocity is positive or negative, then find and average absolute value of both velocities, then give this value to each ball and invert it.

Consistently, the y-velocities are working great and will print to the screen. Also, the gravity, floor and wall collision work perfectly alone. When I try to run this method, however, the x-values for both consistently turn to NaN in text and both balls disappear from the screen.

I have monitored the y-values after the balls disappear and they behave normally under gravity.

What's causing this NaN? If its not a number, how do I find out what it is?

Thanks very much

Tagged:

Answers

  • Also, fAvg returns a float

  • edited February 2016 Answer ✓
    float a = 10, b = 0;
    
    float c = a/b;
    println(c); // Infinity
    
    c *= b;
    println(c); // NaN
    
    println(c != c); // true
    exit();
    
  • Well, I understand what you're saying, but how does that apply to my example? I can't seem to find any case of this, as I only ever multiply.

  • Oh wait, the starting X velocity is 0, that makes perfect sense, thanks!

Sign In or Register to comment.