Я строю небольшую игру 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);
}
}
Когда всходы «игрок», метод Задвижка от объекта игрока называется:
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 хорошо задокументированных строк).
спасибо.
Спасибо за все ответы, я попробую то, что вы упомянули как можно скорее, и вернитесь к каждому! –