我想了解如何在javascript中創建自定義遊戲對象。我在畫布上工作,我認爲可以創建一個包含對象信息的常規遊戲對象位置,形狀等和功能,如「移動」,「火」,「顯示」等的Canvas遊戲體系結構:在JavaScript中訪問父級函數對象
我創建一個名爲「創建(畫布)」函數。獲取畫布並初始化局部變量,然後在「onload」函數中調用顯示函數。 但我無法訪問對象的顯示功能。 此外,我總是使用「this」語法來訪問我的本地變量或函數。這讓我覺得有什麼問題。
你可以看到
<script>
var gameObject = {
x: 0,
y: 0,
velocity: 5,
width: 40,
height: 40,
triggerObject:null,
imgUrl: "/assets/minionframe/1.png",
img:null,
canvas:null,
context:null,
display:function(){
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.context.drawImage(this.img,this.x,this.y,this.width,this.height);
},
move: function (direction) {
if (direction == "right")
x += this.velocity;
else if (direction == "left")
x -= this.velocity;
else if (direction == "up")
y -= this.velocity;
else if (direction == "down")
y += this.velocity;
this.display();
},
fire: function() {
},
create: function (canvas) {
this.canvas = canvas;
this.context = canvas.getContext('2d');
img = new Image();
img.src = this.imgUrl;
img.onload = function() {
this.display()//i cant doing this :(
}
return this;
}
}
</script>
<canvas id="scene" width="800" height="600"></canvas>
<script>
var scene = document.getElementById('scene');
var obj = gameObject.create(scene);
</script>
非常感謝下面的代碼。
非常感謝。它給了我另一個遊戲開發方法的視角。我雖然JavaScript對象的行爲像其他面向對象的編程語言,如C#或Java。所以,我試圖構建一個像Java Object這樣的結構。 –
「img」是一個對象的外觀。我雖然可能是我的遊戲對象的一部分。 –
不客氣!我發現JS開發中的功能風格比「經典」的OO風格更好地工作,上面的設計靈感來自更實用的風格。至於你提到'img'評論,我更新了我的答案(見到底評論) –