Search code examples
javacollision

NaN value being stored to custom "Vector" class


I'm working on a simple platformer for a game jam, but I didn't want to bother using a game engine. What the class "Vector" (I don't think that's the accurate name for what I'm using it for, but whatever) is supposed to do is provide a way to group together to double values, 'x' and 'y', into a single data type and also provide useful calculations, namely "normalize", which takes an input of a vector (in effect a point) and returns a new vector of length one, going in the same direction from the origin. The link to the git hub repository is this: Metroidvania-Template.git

I tried to make it so that when a collision happened, it would find the difference between the last vector and the current one, normalize said vector, and add the normalized vector to the current vector until it no longer collides.


Solution

  • According to the language specification:

    A floating-point operation that has no unique mathematically defined result produces NaN.

    All numeric operations with NaN as an operand produce NaN as a result.

    So, the NaN is appearing either because you are creating a Vector instance with at least one of its coordinates set to NaN; or you are doing a mathematical operation with no unique mathematically defined result.

    As you mention that this is in a method for normalizing the Vector, this is almost certainly arising from the division, where the denominator is zero.

    This means that either you're calculating the denominator incorrectly, or the vector's length really is zero.