Search code examples
actionscript-3nan

what causes as3 code to generate NaN as a result?


I have some collision detection involving lines of arbitrary angles that I can't know ahead of time. I've set up my code to treat them as the form y = mx + b and whenever I create a horizontal line all of the fields come out as NaN. My question is: What operations in AS3 can cause NaN to be returned. The thing that comes to mind is that a perfectly vertical line will have a slope of Number.POSITIVE_INFINITY and I imagine that that could cause potential errors. It shouldn't be on a horizontal line, but logic problems happen. The point is, what causes NaN to be returned in AS3?

package {

    import flash.display.Sprite

    public class Line extends Sprite{

        var x1:Number, x2:Number, y1:Number, y2:Number;
        var m:Number, b:Number; //y = mx + b

    public function Line(x1C:Number, y1C:Number, x2C:Number, y2C:Number){
            x1 = x1C;
            x2 = x2C;
            y1 = y1C;
            y2 = y2C;
            if(x2 - x1 == 0)
                m = Number.POSITIVE_INFINITY;
            else if(y2 - y1 == 0)
                m = 0;
            else
                m = (y2 - y1) / (x2 - x1); //these calculations could be off....
            b = y1 - (m * x1);
            this.graphics.moveTo(x1, y1);
        }

    }

}

Solution

    • Your code may produce a NaN right here:

      b = y1 - (m * x1);
      

    if m is an infinity, and x1 is 0, then multiplying it should result in NaN and this is true not only for AS3.

    • I would recommend you to never use a line equation in a slope-intercept form, that you're using (y = Ax + B), cause you cannot define a vertical line this way. Always use a general form: Ax + By + C = 0.

    • Do not compare floats with ==, always compare floating-point numbers with epsilon. might help. You can have problems in your code if x2 is almost equal to x1.