Question

I'm working on a function that takes the stage mouse coordinates in Flash AS3 and returns tile in a hex-grid below the cursor. I want the function to return NaN or undefined if the cursor is not on a tile and if it is, the integer index of that tile in an object array.

    public function getCursorTile(mX:Number,mY:Number):uint
    {
        var tileIndex:uint = new uint(NaN);
        trace(tileIndex);
        for (i=0; i<tileArray.length; i++)
        {
            if (tileArray[i].hitTestPoint(mX,mY,true))
            {
                tileArray[i].tileBorder.gotoAndStop(1);
                tileIndex = i;
            }
        }
        return tileIndex;
    }

I've been using uint for most integer variables, perhaps this data type doesn't support NaN or undefined? This code traces 0 after tileIndex is defined. I'm using hitTest because the hexgrid isn't square and is randomly generated. Tile 0 is the first tile and returning 0 when the cursor is off the hex-map is going to cause problems.

Was it helpful?

Solution

NaN is of type Number. You can't cast it meaningfully into a uint.

If you really must return NaN, change your function signature to return :Number, but understand that you might take a slight performance penalty for it if that function is on your critical path.

Some C-style trickery could be used here: If meaningful tile indexes are always positive, and you feel confident you won't ever end up with more than 2 billion tiles, you could return -1 to mean "not a tile". You'd need to change :uint into :int, and be careful about implicit conversions between the two types throughout your code.

OTHER TIPS

Another methos is to use the MAX_VALUE of the uint state. In practice you will never reach the value but you can check against it.

Prevents a lot of code refactoring return uint.MAX_VALUE and to check against it if(value == uint.MAX_VALUE). If it is in a enterframe loop you might try to save uint.MAX_VALUE in a const so you don't get the overhead of the variable lookup inside the uint Class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top