我正在用打字稿写一个简单的游戏,这是我的代码的一部分。
class Game {
gamearea : GameArea;
score : ScoreBoard;
started : boolean;
spaceship : Spaceship;
fps : number = 60;
timer : number;
constructor(){
this.gamearea = new GameArea(600, 500);
this.started = false;
this.score = new ScoreBoard(this.gamearea.context, 5, 15);
this.spaceship = new Spaceship(this.gamearea.context,this.gamearea.canvas.width/2, this.gamearea.canvas.height/2);
this.gamearea.add(this.score);
this.gamearea.add(this.spaceship);
this.timer = setInterval(this.mainloop, 1000/this.fps);
}
start(){
this.started = true;
}
mainloop(){
if(this.started){
this.gamearea.clear();
//aggiorno tutto
this.score.increase(1);
//stampo tutto
this.gamearea.draw();
}
else {
clearInterval(this.timer);
//TODO : show start screen
dbg(this.started);
}
}
}
function startGame(){ //this gets called by body.onload
var width = window.innerWidth;
var height = window.innerHeight;
var g = new Game();
g.start();
}
当我打开控制台时,我看到的是每次setInterval触发时打印的undefined
一词,根本没有画布。如果在主循环中尝试打印this的值,则开始打印undefined
如果不是编写类和对象而是将所需的所有内容编写为全局变量和函数,而是显示画布,但是我想将所有内容打包在游戏类中,然后仅通过调用方法游戏开始游戏。 start()。
这是GameArea类:
class GameArea {
canvas : HTMLCanvasElement;
context : CanvasRenderingContext2D;
objects : Drawable[];
constructor(w:number, h:number){
this.canvas = document.createElement('canvas');
this.canvas.id = 'asteroidcanvas';
this.canvas.width = w;
this.canvas.height = h;
this.context = this.canvas.getContext("2d");
this.context.fillStyle = 'black';
this.objects = [];
document.body.appendChild(this.canvas);
}
clear(){
this.context.fillRect(0,0, this.canvas.width, this.canvas.height);
}
draw(){
this.objects.forEach((v)=>{
v.draw();
})
}
add(el: Drawable){
if(el!=undefined){
this.objects.push(el);
}
}
}
并且如果在主循环的第一行,我尝试执行dbg(this.gamearea.canvas.width),每次setInterval触发时,我都会收到“无法读取未定义的属性'canvas'”。 dbg只是console.log的别名