Jump to content

Create random element at run time


nunziox
 Share

Recommended Posts

What is the best way to create an enemy at run time?

 

Actually, i wrote this code:

 

        var position = game.camera.x % 500;        if ((position>= 0&&position<=10&&enemies.countLiving()==0) && game.camera.x != 0) {            var random_number = Math.random() * 100;            if (random_number >= 0 && random_number <= 50) {                enemy = enemies.create(game.camera.x+w, game.world.height - enemyH - solidH, 'enemy');                rifbomb = w;                enemy.body.collideWorldBounds = true;                enemy.frame = 1;                enemy.body.velocity.x = -80;            }        }

 

Link to comment
Share on other sites

The Group object has a method called getRandom which will return a random object from the group. If you create a group with a 'pool' of assorted enemies to pick from, you can call Group.getRandom() on it to pick a random enemy.

 

Of interest, there are other handy utilities for working with random numbers, such as Phaser.Math.getRandom which will pick a random object from a provided array, and Phaser.Math.chanceRoll which will return true or false with a probability based on the number you give it.

            var random_number = Math.random() * 100;            if (random_number >= 0 && random_number <= 50) {

Could be replaced with:

            if (Phaser.Math.chanceRoll(50)) {
Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...