私は小さな 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);
}
}
「プレーヤー」がシュートすると、プレーヤー オブジェクトの shotBolt メソッドが呼び出されます。
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));
}
}
問題は、次のボルトが次のショットごとに速くなることです。発砲すればするほど、彼らは速くなります。また、連射すると複数のボルトが見えるはずですが、撃つたびに前のボルトが消えてしまいます。
これで、ゲームは update 関数と draw 関数をループします。を使用しました
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 行のみ)。
ありがとうございました。