Demo Dynamic Images

Random change images on game ground

by ragesoft

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/3.55.2/phaser.min.js"></script>
<div id="main">

</div>

JavaScript

var maxFrames = 70; 	// some config for how many indiviual frames we got

class Demo extends Phaser.Scene {
    constructor() {
        super({
            key: 'examples'
        })
    }
    
 preload() { 
 
 		// using a spritesheet with all images in one file (same size of frames)
 		this.load.spritesheet( 'groundtiles', 'https://labs.phaser.io/assets/tilemaps/tiles/gridtiles.png', { frameWidth: 32, frameHeight: 32 });
    
    // or load each image individual, like e.g.:
    // than it musst be set via "setTexture" instead of "setFrame"
    /*
    for( let i = 0; i < maxFrames; i++ ){
    	this.load.image( 'groundTile' + i, myURL + "tile' + i + '.png'");
    }
    */
    
    
 }
 
 
 create(){
 
 		this.add.text( 10,10, "Demo-scene for phaser forum request\nhttps://phaser.discourse.group/t/rng-on-images-tiles/11407");
 
 		// creating the ground tiles
 		this.groundTiles = [];
    for( let i = 0; i < 25; i++){
    	let row = Math.floor( i / 5 );
      let col = i%5;
      let frame = Phaser.Math.Between(0, maxFrames );
      let newTile = this.add.image( 100 + col*32, 100 + row*32, 'groundtiles', frame );
    	this.groundTiles.push( newTile );
    }
    
    // periodical change on tiles image 
    setInterval( () => this.changeGroundTile(), 1000);

 }
 
 update(){
 
 }
 /**
  * Randomly change a ground tile 
 **/
 changeGroundTile( ){
 		// get a random item from the groundTiles array
 		let tile = Phaser.Utils.Array.GetRandom( this.groundTiles );
    // change its frame to a new value
    tile.setFrame( Phaser.Math.Between(0, maxFrames ) );
 }
}

var config = {
    type: Phaser.AUTO,
    parent: 'main',
    width: 800,
    height: 600,
    scene: Demo
};

var game = new Phaser.Game(config);