Hi, I want my enemies to spawn randomly on the map (spread out). I have a code that allows them to spawn randomly however the enemies are still quite close together.
Line of code for random spawning:
for (var i = 0; i < blength; i++)
{
this.physics.add.existing (new Enemy(this, Phaser.Math.Between(0, this.game.config.width), Phaser.Math.Between(0, this.game.config.height)));
}
Is there any way i can get them to spawn more randomly and SPREAD out. Much appreciated
You’re just showing us values that are passed into a constructor. We don’t know what is happening in the constructor or what arguments it takes because Enemy
is not a Phaser or Javascript class. Also, for readability sake, try to wrap your code in three back quotes (`).
Example:
for (var i = 0; i < blength; i++)
{
this.physics.add.existing (new Enemy(this, Phaser.Math.Between(0, this.game.config.width), Phaser.Math.Between(0, this.game.config.height)));
}
Ok much appreciated, i’m just slightly new to the forum and phaser itself so was unaware. But my class constructor looks as follows:
class Enemy extends Phaser.Physics.Arcade.Sprite {
constructor(scene, x, y, key, type) {
super(scene, x, y, key, type);
this.scene = scene;
this.x = x;
this.y = y;
this.enemy = this.scene.physics.add.sprite(x, y, 'player2', 'tank1');
}
I want my Enemy to spawn at random points across the map. Currently it spawns random but not spread out enough.
//spawn multiple enemies
for (var i = 0; i < blength; i++)
{
this.physics.add.existing (new Enemy(this, this.rnd.integerInRange(120, 480) ));
}
No worries, everyone’s new at some point.
One thing that I have noticed that you are doing incorrectly is the instantiation of your enemy. Instantiation is the term used for creating an object. In your Enemy
class you are extending Phaser.Physics.Arcade.Sprite
, which means that the class literally is the arcade sprite. This means that you do not need to create an enemy
object within your Enemy
class.
Other than that, the following should work unless your game has scrolling capabilities:
for (var i = 0; i < blength; i++)
{
let enemy = new Enemy(this, Phaser.Math.Between(0, this.game.config.width), Phaser.Math.Between(0, this.game.config.height), 'player2', 'tank1');
this.physics.add.existing(enemy);
}
1 Like