fivesenses99 Posted October 5, 2015 Share Posted October 5, 2015 I am trying to figure out a way to prevent randomly placed sprites without a group from overlapping. For instance the following code will create randomly placed sprites, but is there a feature of phaser than can help me prevent overlap in such a case? Thanks in advance function create() { sprites = game.add.group(); for (var i = 0; i < 30; i++) { var s = sprites.create(game.rnd.integerInRange(0, game.world.width - 32), game.rnd.integerInRange(0, game.world.height - 32), 'diamond'); }} Link to comment Share on other sites More sharing options...
Skeptron Posted October 6, 2015 Share Posted October 6, 2015 I guess you could use the overlap() function and check if newly created sprite is overlapping already existing ones (and move its coordinates until it doesn't). Doc : http://phaser.io/docs/2.3/Phaser.Physics.Arcade.html#overlap Btw, awesome avatar! Link to comment Share on other sites More sharing options...
drhayes Posted October 6, 2015 Share Posted October 6, 2015 Arcade bodies have a property called "embedded" that looks like it'll help: "If a body is overlapping with another body, but neither of them are moving (maybe they spawned on-top of each other?) this is set to true." I've never used it, though, so I'm not sure. Link to comment Share on other sites More sharing options...
alex_h Posted October 6, 2015 Share Posted October 6, 2015 There are a few ways of approaching this problem but one that is nice and simple is to divide the whole area into a grid and then position one sprite randomly within each cell. Link to comment Share on other sites More sharing options...
jmp909 Posted October 6, 2015 Share Posted October 6, 2015 what alex_h said... you don't want to get stuck in a loop where you're trying to randomly place an object and if it overlaps you randomly place it again, only to find it's overlapping again .. could happen, especially the more objects you have. you're going to need to keep track of them manually somehow.. grid cells sounds good to me Link to comment Share on other sites More sharing options...
Skeptron Posted October 7, 2015 Share Posted October 7, 2015 Or you could have the coordinates being some modulo of the sprite's width /height (like {20, 20}, {40, 40}, {60, 60} if your sprite is {20, 20}) and you store the already distributed coordinates, not to give them again. It's a lot like a grid. Link to comment Share on other sites More sharing options...
Recommended Posts