-
-
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).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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