Home > OS >  How to calculate a random position outside the bounds of a rectangle?
How to calculate a random position outside the bounds of a rectangle?

Time:11-30

I'm trying to spawn enemies just outside the bounds of a rectangle. Here's a picture:

enter image description here

That is, the grey area is the playing area that the user can see, and the green is outside the rendering bounds. I'm looking for a way to calculate a spawn position in this green area.

I have a tentative solution, but it's pretty long and involves a bunch of if statements. Is there a more efficient or elegant way of calculating this?

function calcEnemySpawnPos(r) {
  const roll = Math.random();

  const left = -r;
  const right = canvas.width   r;
  const top = -r;
  const bottom = canvas.height   r;

  if (roll <= 0.25) {
    return { x: left, y: getRandomInt(top, bottom) };
  } else if (roll <= 0.5) {
    return { x: right, y: getRandomInt(top, bottom) };
  } else if (roll < 0.75) {
    return { x: getRandomInt(left, right), y: top };
  } else {
    return { x: getRandomInt(left, right), y: bottom };
  }
}

CodePudding user response:

Just pick two random numbers x, y in the range 0-200.

For x, if x < 100 subtract 100, otherwise add 400. For y, if y < 100 subtract 100, otherwise add 200.

CodePudding user response:

I have a slight improvement, but still not amazingly elegant. This is pseudocode since I'm not sure of the js syntax:

const rollLeft = Math.random() - 0.5;
const rollTop = Math.random() - 0.5;

if (rollLeft > 0){
    x = getRandomInt(-r, 0)
} else {
    x = getRandomInt(canvas.width, canvas.width   r)
}
    
if (rollRight > 0){
    y = getRandomInt(-r, 0)
}   else {
    y = getRandomInt(canvas.height, canvas.height   r)
}

return {x, y}

CodePudding user response:

Here's an idea. Maybe parameterize the magic numbers.

function startPos() {
    const r = Math.round(Math.random() * 200 * 200);
    const x = r % 200;
    const y = (r-x) / 200;
    return [x < 100 ? x-100 : x 400, y < 100 ? y-100 : y 200];
}
  • Related