Jump to content

Add random sprites without overlap


smartgoat
 Share

Recommended Posts

Hello, I want to create a game using Phaser. I want to add sprites randomly, but they shouldn't overlap each other. What is the best practice to achieve this. Here is my code, but I saw overlapping sprites sometimes:

var obstacles = [];
var items = [];

function loadMap ()
{
    for (i = 0; i < 100; i++)
    {
        var obs = game.add.sprite(game.world.randomX, game.world.randomY, 'obstacle');
        game.physics.enable(obs, Phaser.Physics.ARCADE);
        obstacles.push(obs);
    }
}

function loadItems ()
{
    for (i = 0; i < 36; i++)
    {
        var item = game.add.sprite(game.world.randomX, game.world.randomY, 'item');
        game.physics.enable(item, Phaser.Physics.ARCADE);
        while (checkOverlapMany(item, items) || checkOverlapMany(item, obstacles))
        {
            item.x = game.world.randomX;
            item.y = game.world.randomY;
            
            sleep(80);
        }
        items.push(item);
    }
}

function checkOverlapMany(sprite, list)
{
    for (var i = 0; i < list.length; i++)
    {
        if (game.physics.arcade.overlap(sprite, list )) return true;
    }
    
    return false;
}

 

Link to comment
Share on other sites

I noticed you are not enabling physics on the items.

In addition to this, you are passing the entire list to be checked for overlap here:

if (game.physics.arcade.overlap(sprite, list)) return true;

You probably meant to index that list.

Link to comment
Share on other sites

22 hours ago, Zeterain said:

I noticed you are not enabling physics on the items.

In addition to this, you are passing the entire list to be checked for overlap here:


if (game.physics.arcade.overlap(sprite, list)) return true;

You probably meant to index that list.

Thanks for your reply. I fixed the code as you said but the situation still the same. Is there any suggestion?

Note: I cannot add

Quote

[ i ]

to the above post, it seems there is a problem of code renderer

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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