Sign in to follow this  
nunziox

Create random element at run time

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;            }        }

 

Share this post


Link to post
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)) {

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.