簡體   English   中英

如何運行一個對象的多個實例

[英]How to run multiple instances of one object

我對OOP Javascript非常陌生,我正在嘗試通過構建游戲來學習。 在游戲中,您基本上是一個正方形,而其他正方形從右邊向您襲來。 聽起來很簡單。 您基本上可以通過上下移動來避免它們,如果它們碰到您,您就會喪命。 我已經做了一個Player對象:

function Player() {
this.color = "#0f0";
this.posx = canvas.width / 5;
this.posy = canvas.height / 2;
this.width = canvas.width / 23;
this.height = this.width;
this.jetpack = false;
this.speed = 7;

this.draw = function() {
    context.fillStyle = this.color;
    context.fillRect(this.posx, this.posy, this.width, this.height);
}

this.fly = function() {
    if (this.jetpack == true) {
        this.posy -= this.speed;
    } else {
        this.posy += this.speed * 1.5;
    }

    if (this.posy >= canvas.height - this.height) {
        this.posy = canvas.height - this.height;
    }

    if (this.posy <= 0) {
        this.posy = 0;
    }
}
}

然后我可以用

var player = new Player();

那很好。

我有一個主要功能,基本上是一個間隔,每秒運行30次,重復以下代碼:

context.fillStyle = "#000";
context.fillRect(0, 0, canvas.width, canvas.height);

player.draw();
player.fly();

這會吸引播放器,並使您可以很好地移動它。 問題來自敵人。 我有這樣定義的敵人對象:

function Enemy(posy) {
this.color = "#f00";
this.posy = posy;
this.posx = canvas.width;
this.width = canvas.width / 23;
this.height = this.width;
this.speed = 5;

this.draw = function() {
    context.fillStyle = this.color;
    context.fillRect(this.posx, this.posy, this.width, this.height);
}

this.move = function() {
    this.posx -= this.speed;
}
}

但是我不知道如何正確召喚它。 目標是每隔一秒鍾左右產生一個新的,它們都會移動。 我不知道該怎么做。很難找到在線幫助,因為我什至不知道如何稱呼它,因此,我不確定應該尋找什么以及如何正確表達自己的想法。 我希望這足夠清楚...

首先,您將創建一個與玩家相同的敵人:

const enemy = new Enemy(123); // change 123 to a random value

但是,您要做的是在創建敵人時將它們放置在數組中:

// make sure this is in an appropriate place to maintain proper context
// probably the same level you define your player variable
const enemies = []; 

function addEnemy() {
  enemies.push(new Enemy(Math.random() * screenHeight)); // screenHeight will be whatever the max height for them to spawn is.
}

然后,您可以遍歷該函數並將其全部移動:

enemies.forEach(enemy => enemy.move());

在某些時候,您還想移除敵人(當敵人擊中物體或離開屏幕時),您需要使用splice()進行以下操作:

enemies.splice(indexOfEnemyToRemove, 1);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM