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

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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

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