2016-10-15 13 views
0

私はJavascriptのゲームにはかなり新しいので、分かりやすい質問があれば気にしないでください。 私はフロッグゲームに取り組もうとしています。このために私はオブジェクトを持っています。そして、新しいコンストラクタを一貫して作成したいので、バグがたくさんあるように見えるはずです。Javascript game自動的に新しいオブジェクトを作成して配列に連続的に追加する[javascript]

これは私の敵のオブジェクトです。

// Enemies our player must avoid 
var Enemy = function(x,y) { 
    // Variables applied to each of our instances go here, 
    // we've provided one for you to get started 

    // The image/sprite for our enemies, this uses 
    // a helper we've provided to easily load images 
    this.sprite = 'images/enemy-bug.png'; 
    this.x = x; 
    this.y =y; 
}; 

// Update the enemy's position, required method for game 
// Parameter: dt, a time delta between ticks 
Enemy.prototype.update = function(dt) { 
    // You should multiply any movement by the dt parameter 
    // which will ensure the game runs at the same speed for 
    // all computers. 

    this.x = this.x+((Math.random() * (15 - 1 + 1) + 1)*dt*35); 

    this.y = this.y; 
}; 

// Draw the enemy on the screen, required method for game 
Enemy.prototype.render = function() { 
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y); 
}; 

し、私は私が唯一のバグの単一の列を見ることができる配列

// Place all enemy objects in an array called allEnemies 
var allEnemies=[]; 
allEnemies.push(new Enemy(0,135)) 
allEnemies.push(new Enemy(0,225)) 
allEnemies.push(new Enemy(0,50)) 

に手動でそれらを押してください。私はこれを上記のシナリオが自動的に起こるようにしたい、私はここでコール関数を使用する必要があると思ったが、それでも私は好む連続的な間隔で自動的にそれを行う必要があります。

+2

連続した間隔で起こるようにするにはsetIntervalを使用できます – Geeky

答えて

1

ヨアヒム氏のようにwindow.setInterval()を使用するか、window.requestAnimationFrame()を使用するか、window.setTimeout()を使用することもできます。私は個人的には、特にアニメーションやレンダリングのためのブラウザであるため、ブラウザでrequestAnimationFrame()を使用することをお勧めしますが、ノード環境で何かをしている場合は、setIntervalに行ってください。

それ以外は、敵のすべての新しいインスタンスを配列にプッシュすることがわかりました。追加された1つのステートメントでこれを行うことができます。あなたがそうのようなオブジェクトを作成するたび また、アレイにプッシュすることができます:

var allEnemies = []; 

function Enemy(x,y){ 
    this.x = x || (Math.random() * WIDTH) | 0; 
    this.y = y || (Math.random() * height) | 0; 
    this.sprite = "bug-sprite-thing"; 
    allEnemies.push(this); // this is called every time you do `new Enemy(n,n) 
    // the new object will automatically be pushed to the array. 
} 

をあなたはランダムな間隔で新たな敵を起動したい場合は、この関数は何setTimeout

var MINIMUM = 100; // 0.1 seconds 
var MILLISECONDS = 10000; // 10 seconds 
function spawnAtRandom(){ 
    // add your code here. 
    setTimeout(spawnAtRandom, minimum + (Math.random() * (MILLISECONDS-MINIMUM))); 
} 
spawnAtRandom(); 

を使用することができます開始時に1つのものが生成され、次にランダムな間隔で何かを生成するように進みます。MINUMUMMILLISECONDS

+0

しかし、私はどのようにランダムな間隔で新しい敵を呼びますか? –

+0

私の答えをちょうど更新しました。 – ahitt6345

1

だけwindow.setInterval()を呼び出す:

var allEnemies = []; 
window.setInterval(function() { 
    allEnemies.push(new Enemy(0, 135)); 
}, 2000); 

これは(あなたにもランダム化する可能性が)同じ位置にあなたの配列に2秒ごとに新しいEnemyオブジェクトを作成します。

関連する問題