我在构建游戏时从这本 JS 书中获得了这种迷你框架(场景、演员)。我将在这里显示代码并在之后提出问题:
//-------------------------------SCENE CLASS------------------------------//
function Scene(context, width, height, images)
{
this.context = context;
this.width = width;
this.height = height;
this.images = images;
this.actors = [];
}
Scene.prototype.register = function(actor)
{
this.actors.push(actor);
}
Scene.prototype.unregister = function(actor)
{
var index = this.actors.indexOf(actor);
if(index >= 0)
{
this.actors.splice(index,1);
}
}
Scene.prototype.draw = function()
{
this.context.clearRect(0, 0, this.width, this.height);
for(var i = 0;i < this.actors.length; i++)
{
this.actors[i].draw();
}
}
//-------------------------------ACTOR CLASS-------------------------------//
function Actor(scene, x, y)
{
this.scene = scene;
this.x = x;
this.y = y;
scene.register(this);
}
Actor.prototype.moveTo = function(x, y)
{
this.x = x;
this.y = y;
this.scene.draw();
}
Actor.prototype.exit = function()
{
this.scene.unregister(this);
this.scene.draw();
}
Actor.prototype.draw = function()
{
var image = this.scene.images[this.type]; // how does this work???
this.scene.context.drawImage(image, this.x, this.y);
}
Actor.prototype.width = function()
{
return this.scene.images[this.type].width;
}
Actor.prototype.height = function()
{
return this.scene.images[this.type].height;
}
//-----------------------------SPACESHIP CLASS------------------------------//
function Spaceship(scene, x, y)
{
Actor.call(this, scene, x, y);
}
Spaceship.prototype = Object.create(Actor.prototype);
Spaceship.prototype.left = function()
{
this.moveTo(Math.max(this.x - 10, 0), this.y);
}
Spaceship.prototype.right = function()
{
var maxWidth = this.scene.width - this.width();
this.moveTo(Math.min(this.x + 10, maxWidth), this.y);
}
Spaceship.prototype.type = "Spaceship";
我的问题是,对于这个宇宙飞船示例或可能出现的任何其他演员对象,您如何将图像插入到场景构造函数中?它在书中非常含糊地说要创建一个“数据表”,但我不知道该怎么做。如果我想利用这个类,我想我必须做这样的事情:
var scene = new Scene(ctx,800,600, //not sure here)
var spaceship = new Spaceship(scene,10,10);
scene.draw();
谢谢!:)