virajsoni Posted February 27, 2015 Share Posted February 27, 2015 Hello game makers, I'm making my first game wherein the target/enemies appear randomly on the screen and go off the screen after a specific time. I've got most of it figured out, but the only problem I'm facing is how do I place them randomly such that they do not overlap each other. Here's my code to create enemies. addTargetToGroup: function() { // Add Target var targetInsideWidth = this.game.stage.bounds.width - this.cache.getImage('target').width; var targetInsideHeight = this.game.stage.bounds.height - this.cache.getImage('target').height; this.newTarget = this.targetGroup.create(this.rnd.integerInRange(0, targetInsideWidth), this.rnd.integerInRange(0, targetInsideHeight), 'target', 0); this.newTarget.anchor.setTo(0.5, 0.5); this.newTarget.enableBody = true; // Add different animations for target hit this.newTarget.animations.add('gunHit', [0,1,0]); this.newTarget.animations.add('balloonHit', [1,0,1,1,0,1,1,0,1,1,0,1]); ; this.newTarget.uniqueId = 'targetId-'+i; i++; this.newTarget.spawnedIndex = spawnArea.indexOf(targetLocation); // console.log(this.newTarget.spawnedIndex) // Enable click on targets this.newTarget.inputEnabled = true; this.newTarget.events.onInputDown.add(this.hitTarget); },Any help would be great. Cheers Link to comment Share on other sites More sharing options...
Tom Atom Posted February 28, 2015 Share Posted February 28, 2015 This is more general game programming question than Phaser question. But, anyway, this is solution I used for similar problem in past: - create and place you new enemy at random position,- calculate bounding circle around your new enemy (is symmetric then width / 2 will be the radius),- iterate through all previous enemies,- for enemy each enemy calculate bounding circle too,- check if circles overlap (length of vector from center to center is less than sum of both circles's radii),- if overlap then push new sprite in direction of that vector between centers, so bounding circles do not overlap anymore, - repeat the iterations again until there is no need to push new enemy (in fact, if your screen is not crowded then very few iterations will be needed, also limit it to 5 or 6) Link to comment Share on other sites More sharing options...
jimbug Posted March 1, 2015 Share Posted March 1, 2015 Imagine your enemies are just rectangles.You can place the first enemy anywhere you want. After that first placement you must start keeping track of the x,y ranges where each newly created enemy is. For this, you may use an array, an object or two arrays. So next time you generate a new random coordinate it is outside of those ranges. Link to comment Share on other sites More sharing options...
Recommended Posts