How can I randomize the position of spawned enemies?

I have a function in my main phaser Game class as shown below:

spawnBaddies(){
    enemyGrunts.createMultiple({
        key: 'enemyGrunt', 
        repeat: gruntAmount - 1,
        setXY: { x: (Phaser.Math.Between(0, config.width)), y: 0, stepX: 0 } 
    })
    enemyGrunts.children.iterate(function(child){
        child.setVelocity(0, Phaser.Math.FloatBetween(gruntMinSpeed, gruntMaxSpeed)); //Randomize the y-component of the velocity per child spawned
    });
}

My code works in that it changes the position that the enemies start spawning from every time.
However, it changes the starting position so that every child created starts from that same random position.

I would like to make it so that each child created has it’s own unique starting position along the x-axis. I tried the stepX parameter but that will just offset the random position of each child by the same amount and the offset would always be to the right of the starting x position. How would I got about doing this properly?

Set the position to a random number for each enemy individually. You’re already iterating the group to set velocities, so instead of using setXY in the createMultiple config, set the position using child.setPosition(<random number>, 0) in the iterate callback.

2 Likes

Oh wow this is a much simpler solution to the problem haha.
Can’t believe this didn’t cross my mind.

Thank you!