我正在尝试创建一个简单的游戏循环并尝试在 JS 中使用 OOP 范例。这是我的代码:
HTML
<body onload="Game.OnLoad('gameField')" onkeydown="Game.KeyDown(event)">
<p id="info">1</p>
<p id="info2">2</p>
<canvas id="gameField"
width="896px"
height="717px"
class="game-field"
style="border: 4px solid aqua"
onclick="Game.MouseClick(event)"></canvas>
</body>
JavaScript
// class Timer
// version: 1
// only tick() functionality available
// right now
function Timer() {
var date = new Date();
var prevTick = 0;
var currTick = 0;
// update timer with tick
this.tick = function() {
prevTick = currTick;
currTick = date.getTime();
}
// get time between two ticks
this.getLastTickInterval = function() {
return currTick - prevTick;
}
}
// global object Game
// which handles game loop
// and provide interfaces for
var Game = new function() {
// variables:
this.canvas = 0;
var gameLoopId = 0;
this.timer = new Timer();
// events:
this.KeyDown = function(e) {}
// game loop:
this.Run = function() {
this.timer.tick();
this.Update(this.timer.getLastTickInterval());
this.Draw();
}
this.Update = function(dt) {
document.getElementById("info").innerHTML = dt;
}
this.Draw = function() {}
this.StopGameLoop = function() {
clearInterval(gameLoopId);
}
this.OnLoad = function(canvasName) {
this.canvas = document.getElementById(canvasName);
this.timer.tick();
// start game loop
setInterval(this.Run, 1000);
}
}
(小提琴)
我正在尝试使 Game 类全球化。其他类必须使用new
.
类 Game 和 Timer 放置在名为 Game.js 和 Timer.js 的不同文件中。当我在 Chrome 中运行此代码时,我在 DevTools 中遇到错误:行"Uncaught TypeError: Cannot call method 'tick' of undefined"
中的Game.Run
函数this.timer.tick();
所以我想知道,我的代码有什么问题?谢谢您的回复。