Skip to content

Instantly share code, notes, and snippets.

@FireyFly
Forked from robotlolita/gist:2941344
Created June 16, 2012 13:38
Show Gist options
  • Save FireyFly/2941356 to your computer and use it in GitHub Desktop.
Save FireyFly/2941356 to your computer and use it in GitHub Desktop.
Get a random Y position for a new enemy being spawned, which is NOT "crowded" (no other active enemy must have the same rough Y position).
function getYPositionNotCrowded() {
var maxCount = 1000
, height = 4
, i = 0
, y
do {
y = nextYPosition()
if (++i > maxCount) { throw new Error("No position found!") }
} while (isCrowded(y))
return y
//-- Helpers ----------------------------------
function nextYPosition() {
return Math.floor(Math.random()*WIDTH)
}
function isCrowded(y) {
// Check if at least one enemy is in the way.
// (In that case we know immediately that the y pos is crowded.)
return enemies.some(function(enemy) {
// Bounds
var lower = enemy.y - height/2
, upper = enemy.y + height/2
// Check if within bounds
return lower <= y && y <= upper
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment