我建立一個小型的JavaScript遊戲,但在教程和諸如此類的東西在網上看後,它只是不是爲我工作。爲了節省一些麻煩,以下是我認爲可能出錯的部分(實際問題在下面進行了更多解釋)。簡單的JavaScript遊戲:可能的對象數組錯誤
它運行在一個非常基本的循環,現在,我有一個數組來保存玩家的螺栓,他瞪了他們:
var playerBolts=new Array(); //Holds all the bolt objects that the player shoots
setInterval(function(){
updateGame();
drawGame();
},25);
這是創建玩家射擊時,螺栓對象。
function bolt(facing,playerX,playerY){ //The bolt object is shot from the player's current position
this.facingLeft=facing; //The direction at which the bolt moves, if left, true
this.x=playerX; //The x position of the bolt
this.y=playerY; //The y position of the bolt
if(facingLeft==true){
this.xSpeed=-3; //The horizontal speed at which the bolt is moving
}
else if (facingLeft==false){
this.xSpeed=3;
}
this.ySpeed=0; //The vertical speed at which the bolt is moving
this.W=3; //The width of the bolt's model
this.H=3; //The height of the bolt's model
this.color="red"; //The color of the bolt's model
this.update=update;
function update(){ //Updates the bolt's properties
this.x=this.x+this.xSpeed;
this.y=this.y+this.ySpeed;
}
this.draw=draw;
function draw(){ //Draws the bolt's model to the canvas
context.fillStyle=this.color;
context.fillRect(this.x, this.y, this.W, this.H);
}
}
當「運動員」衝量,從播放器對象shootBolt方法被稱爲:
function player(){ //The player object
this.facingLeft=true; //If the player's character is facing left, true
this.x=100; //The x position of the player
this.y=100; //The y position of the player
this.shootBolt=shootBolt;
function shootBolt(){ //Shoots a bolt, creating a new bolt object and adding it to the playerBolts array
playerBolts.push(bolt(this.facingLeft,this.x,this.y));
}
}
的問題是,下一個螺栓變快每隔以下射門。你越開心,他們得到的速度就越快。此外,如果快速射擊,應該有多個可見的螺栓,但每次射擊時,前一個都會消失。
現在的遊戲遍歷更新和借鑑作用。我用了一個用於
function updateGame(){ //The main update phase
player1.update(); //Updates the player's properties
playerBolts.forEach(function(bolt){ //Updates all active bolts's properties
this.update();
});
}
function drawGame(){ //The main drawing phase
context.fillStyle="white";
context.fillRect(0,0,canvasW,canvasH); //Clears the canvas for the next frame
player1.draw(); //Draws the player
playerBolts.forEach(function(bolt){ //Draws all bolt's model to the canvas
this.draw();
});
}
所以啊...我認爲這可能與我添加對象與「推」到數組中,「的forEach」的方法(順便做,雖然我已經試過一個for循環)。我不知道自己做錯了什麼,並且我已經查找了源代碼,而且這應該是不行的?如果沒有足夠的信息,我總是可以發佈全部內容(只有119條記錄良好的文字)。
謝謝。
謝謝你所有的答案,我會嘗試你提到的東西,儘快回覆給大家! –