Actionscript3,为什么会发生这种情况?

时间:2014-02-28 21:25:34

标签: actionscript-3

我得到每帧的增量时间,这就是我的工作方式..

private var currFrame:Number,lastFrame:Number,delta:Number,playerX:Number = 10;
public function step(e:Event):void 
    {   
        trace(playerX);
        currFrame = getTimer();
        delta = (currFrame - lastFrame) / 1000;
        lastFrame = currFrame;

        playerX += (delta);
    }

结果是每帧都有'NaN'。但这有效

     private var currFrame:Number,lastFrame:Number=0,delta:Number,playerX:Number = 10;
     public function step(e:Event):void 
    {   
        trace(playerX);
        currFrame = getTimer();
        delta = (currFrame - lastFrame) / 1000;
        lastFrame = currFrame;

        playerX += (delta);
    }

如果你没有注意到的区别是“lastFrame:Number = 0”

任何想法为什么,我从java移动到Actionscript3,所以越多的信息越好:)

gettimer是这样的:import flash.utils.Timer;

1 个答案:

答案 0 :(得分:0)

您的代码lastFrame:Number=0在创建时将lastFrame的值设置为0。如果lastFrame的值未设置为0,则其值为undefined。在AS2中,undefined将被视为0.在AS3中,undefined被视为NaN

使用NaN进行任何计算都会返回NaN。例如:5 + NaN = NaN。因此,当您第一次运行函数时,您正在执行此操作:

delta = (currFrame - NaN) / 1000; //set delta to NaN
lastFrame = currFrame; // sets lastFrame to something besides NaN

playerX += (delta); //sets playerX to NaN

现在,您的lastFrame不是NaN,似乎事情应该有效,但playerX现在是NaN,所以行:

playerX += (delta); // will always be NaN now, even if delta is not NaN

将玩家X永远保持在NaN。因为NaN + Anything仍然是NaN。因此,NaN += Anything始终为NaN