Jump to content

Prevent randomley generating platforms from overlapping?


jg7183
 Share

Recommended Posts

Hey guys, I've searched high and low for a way to solve this but I can't seem to find anything :(

Anyway.

 

So I've created a platform group and in the create function I've added a for loop which creates 6 platforms at randomX,randomY locations.

function create(){for(numPlatforms = 0; numPlatforms < numNeeded;numPlatforms++){  platforms.create(game.world.randomX -100,game.world.randomY -100 ,'platform');}; 

Only problem is when the page loads there is a very good chance that some of my platforms will overlap. 

As seen here. 65c65a8158c0c1a0a3594ceb15321284.png

Does Phaser have something built in which can fix this? Or if not what kind of algorithm would I use to ensure my platforms are properly spaced? I've tried collision checking but from I'm seeing because the platforms physically spawn on top of each other when the page loads they don't count as collided. 

 

Link to comment
Share on other sites

Hi,

 

This example has a routine which generates a load of trees on a grid, ensuring none of them overlap. This is a typical method for ensuring you get properly spaced objects that don't overlap.

 

http://examples.phaser.io/_site/view_full.html?d=groups&f=depth+sort.js&t=depth%20sort

 

What this does is known as "generate and test": makes random ones, tests for duplicates.

You can do a more elaborate overlap test and still use the same principle even if you are not happy with the platforms snapping to a grid like those trees are.

Oh, and make sure you stop trying after a while if the boundaries are too tight and you are not finding enough good ones in reasonable time :-)

Link to comment
Share on other sites

  • 2 weeks later...

This example has a routine which generates a load of trees on a grid, ensuring none of them overlap. This is a typical method for ensuring you get properly spaced objects that don't overlap.

 

http://examples.phaser.io/_site/view_full.html?d=groups&f=depth+sort.js&t=depth%20sort

 

 

Can anybody please explain this function from the example to me? I really can't figure out where the numbers 17 in the if condition and 32 in the var declaration come from.

function createUniqueLocation() {do {var x = game.math.snapTo(game.world.randomX, 32) / 32;var y = game.math.snapTo(game.world.randomY, 32) / 32;if (y > 17){y = 17;}var idx = (y * 17) + x;}while (locs.indexOf(idx) !== -1)locs.push(idx);group.create(x * 32, y * 32, 'trees', game.rnd.integerInRange(0, 7));}
Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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