Jump to content

Create group with multiple sprites at random positions


Recommended Posts

In Phaser 3 is it possible to create a group and add multiple sprites at random positions?

I've tried looking at the documentation here and the example here but couldn't figure out how to do it.

This is my code so far, it does add one coin at a random position each time I run it, butit only seems to add one single coin.

        // add random coins
        var coins = this.add.group();
            key: 'sprites',
            frame: 'coin1',
                x: Phaser.Math.RND.between(0, 800),
                y: Phaser.Math.RND.between(0, 600)
            frameQuantity: 2,
            repeat: 5

Coming from Phaser v2, I've just started working with Phaser 3 and it takes some time to get to understand the differences.

Link to comment
Share on other sites

If you console.log the group - console.log(coins.children.entries) What is the length/size of the group? It's possible that you're creating all the coins you need but they're all being put on the same spot. If that's the case then it's because your call to random only happens once when the create multiple function is called. I guess it's because the function isn't a loop and so only acts on the parameters you provide. 

I'm not massively in the know about phaser, but you could try to circumvent this by simply creating coins in a loop and then adding them to the group. This way the random number will be new each iteration of the loop. 

Hope that helps.

Link to comment
Share on other sites

Thanks @NoxBrutalis I was focusing to much on the .createMultiple() method. Simply creating the coins in a loop and then adding them to the group worked for me :)

	this.gameitems = this.physics.add.group();

	for (var i = 0; i < 20; i++) {
		var x = Phaser.Math.RND.between(0, 800);
		var y = Phaser.Math.RND.between(0, 600);

		var newobj = this.gameitems.create(x, y, 'sprites', 'coin1');

Btw is there a way to get the width and height values (800 and 600) from the current scene or game instead of using hardcoded numbers for the RND function?

Link to comment
Share on other sites

I believe that the the dimensions you give to the game config are the size of the camera's viewport rather than the world's dimensions, but if your camera is the extent of your world - you wont be implementing scrolling and you want everything in your scene to be visible etc, then you can access the camera. In my own project I just use this :



and the next thing can be either width, height, x or y. So depending on the complexity of your scene/camera, you could just use that.

Link to comment
Share on other sites

  • 10 months later...

  • Recently Browsing   0 members

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