How to make a randomly selected element?

Need to select a random sprite from this example.

https://labs.phaser.io/edit.html?src=src/game%20objects/group/random%20frame.js

Remake like with mummies.

https://labs.phaser.io/edit.html?src=src\animation\start%20from%20random%20frame.js

Mummies also use the random function.I just can’t figure it out.How to select one element from a large list of sprites.Already made an example, but forsome reason the element is not randomly selected?

Here is the code

<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
</head>

<body>
  
  <script src='https://cdnjs.cloudflare.com/ajax/libs/phaser/3.22.0/phaser.min.js'></script>
      <script>

class Example extends Phaser.Scene
{
    preload ()
    {
        this.load.setBaseURL("//PhaserAnim.su/");
       
        this.load.spritesheet('bobs', 'assets/sprites/bobs-by-cleathley.png', { frameWidth: 32, frameHeight: 32 });
    }

    create ()
    {
        //  This will create a Group with 400 children.
        //  Each child will use the 'bobs' texture and a random frame number between 0 and 399 (inclusive)
        //  Change 'randomFrame' to false to see the difference it makes
        //const sprite1 = this.add.sprite(50, 100, 'bobs').setScale(4);
        this.anims.create({
            key: 'step',
            frames: Phaser.Utils.Array.NumberArray(0, 399),
            frameRate: 399,
            repeat: -1
        });
       const sprite1 = this.add.sprite(50, 100, 'bobs').setScale(4);
       
       sprite1.play({ key: 'step', randomFrame: true});
       /* const group = this.make.group({
            key: 'bobs',
            frame: Phaser.Utils.Array.NumberArray(0, 399),
            randomFrame: true,
            gridAlign: {
                x: 16,
                y: 16,
                width: 25,
                height: 25,
                cellWidth: 32,
                cellHeight: 32
            }
        });*/
    }
}

const config = {
    type: Phaser.AUTO,
    parent: 'phaser-example',
    width: 800,
    height: 600,
    scene: Example
};

const game = new Phaser.Game(config);

</script>

</body>

</html>

For selecting a random sprite from the spritesheet, one of the ways you can do this is by providing a random frame number when you create your Sprite Game Object. In the code below:

you can add one more argument to provide the frame you want to use. Example:

const sprite1 = this.add.sprite(50, 100, 'bobs', 1).setScale(4);

This would result in the frame 1 being used for the Sprite. By default, if this is omitted, Phaser will use the 0 indexed frame, which is why your sprite has the same frame each time. For a random frame, you could do something like:

const sprite1 = this.add.sprite(50, 100, 'bobs', Phaser.Math.RND.between(0, 399)).setScale(4);

This will generate a random number between 0 and 399, and each time you refresh you re-run your Phaser Scene, a random sprite should be shown.

1 Like