被NaN迷惑-HTML CANVAS JS

时间:2020-07-22 09:08:13

标签: javascript canvas nan

我正在尝试在一个对象中创建一个计时器-但是,当尝试在经过的时间之前增加计数器时,出现了NaN错误。如果我用一个常数替换deltaTime参数,该错误将停止,但是跳转时间将根据最终用户的机器和工作负载而变化。

class Actor {
    constructor() {
        this.jumpCounter =  0

        this.jumpTimer = function (deltaTime) {
            console.log(this.jumpCounter);
            this.jumpCounter += deltaTime;
            console.log(deltaTime)
        }
    }
}

let canvas = document.getElementById('gameScreen');
let ctx = canvas.getContext("2d");
var lastTime = 0; 

const GAME_WIDTH = 600; 
const GAME_HEIGHT = 600;

actor = new Actor;

function gameLoop(timestamp) {
    let deltaTime = timestamp - lastTime;
    lastTime = timestamp;
   
    ctx.fillStyle = 'rgba(155, 200, 155, 0.3)'
    ctx.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT);

    actor.jumpTimer(deltaTime)
    requestAnimationFrame(gameLoop);
}

gameLoop();
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Game Sandbox</title>
    <style>
        #gameScreen {
            border: 1px solid;            
        }
    </style>

</head>
<body>
    <canvas id="gameScreen" width="600" height="600"></canvas>
    <script></script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

由于错误是由于第一次运行代码时出现时间戳而导致的,因此解决了该问题:

        this.jumpTimer = function (deltaTime) {
            if (!deltaTime) return;    
            console.log(this.jumpCounter);
            this.jumpCounter += deltaTime;
            console.log(deltaTime)
        }