我正在构建一个小型 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 行有据可查)。
谢谢你。