0
我有這種迷你框架(場景,Actor)來構建我從這本JS書中獲得的構建遊戲。我會在這裏顯示的代碼後提出這樣的問題:用於Canvas的面向對象的JavaScript
//-------------------------------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();
謝謝! :)
非常感謝您的回覆!我很好奇,你會如何指定IMAGE_DATA?這是圖像本身的src嗎? – westcoaster83 2013-03-14 21:27:45
這取決於場景的上下文類是如何設置的。看看那個班的文件。 – 2013-03-15 02:48:05
因此,在此處的示例中,您將圖像放在HTML上的圖像上,並帶有id爲「spaceShipImageId」的HTML。我只是不知道你的意思是IMAGE_DATA。實際上,沒有任何有關Scene類的文檔......幾乎就是您在代碼示例中看到的內容。 – westcoaster83 2013-03-15 07:21:45