[英]JavaScript: change a variable with a prototype function inside the constructor
[英]Javascript constructor variable NAN inside function
我試圖跟蹤發生的所有可能性,但是我正在學習Javascript,因此它一定是我不知道的東西。 具體的問題在pongGame構造函數/函數中。 但是,我包含了我的整個代碼,只是為了確保有必要。 我假設在pongGame構造函數中聲明的gameLoop函數中,變量pongGame.delta等於10; 因為,這就是我聲明的那樣。 但是,它等於NaN。 這里到底發生了什么問題? 謝謝 :)
var keys = [false, false, false, false];
var cavnas = document.getElementById("canvas");
var context = cavnas.getContext("2d");
(function() {
startUp();
})();
function startUp() {
resize();
window.addEventListener("resize", resize);
var game = new pongGame();
game.start();
}
function resize() {
document.getElementById("canvas").width = window.innerWidth;
document.getElementById("canvas").height = window.innerHeight;
}
function pongGame() {
this.delta = 10;
this.lastTime = 0;
this.ball = new ball();
this.start = function() {
this.gameLoop();
}
this.update = function() {
this.ball.update();
}
this.render = function() {
context.clearRect(0, 0, window.innerWidth, window.innerHeight);
this.ball.render();
}
var pongGame = this;
this.gameLoop = function(timestamp) {
console.log(pongGame.delta); // 10
pongGame.delta += timestamp - pongGame.lastTime;
while (pongGame.delta > (1000 / 60)) {
pongGame.update();
pongGame.delta -= (1000/60);
}
pongGame.render();
pongGame.lastTime = timestamp;
requestAnimationFrame(pongGame.gameLoop);
}
}
function paddle() {
}
function ball() {
this.x = 1;
this.y = 1;
this.xspeed = 1;
this.yspeed = 1;
this.size = 10;
this.update = function() {
if (this.x == 0 || this.x == window.innerWidth - this.size) {
this.xspeed = -this.xspeed;
}
if (this.y == 0 || this.y == window.innerHeight - this.size) {
this.yspeed = -this.yspeed;
}
this.x += this.xspeed;
this.y += this.yspeed;
}
this.render = function() {
context.beginPath();
context.arc(this.x, this.y, this.size, 0, Math.PI * 2);
context.fill();
}
}
第一次調用gameLoop
您不會傳遞時間戳,因此此表達式pongGame.delta += timestamp - pongGame.lastTime;
將delta
首次運行設置為NAN,然后將其自NAN以來的所有后續運行(具有時間戳)設置為。
也許第一次用0來稱呼它
this.start = function() {
this.gameLoop(0);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.