smartgoat

Add random sprites without overlap

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

 

Share this post


Link to post
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.

Share this post


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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.