You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何优雅计算矩形边界外的随机敌人出生位置?

优化敌人出生位置计算代码

你要在可视矩形区域外生成敌人,原来的代码靠多分支判断实现,但其实可以把四条边的生成逻辑抽出来,简化冗余代码,同时保持逻辑清晰。

优化思路

把四个边的生成规则做成数组里的函数,随机挑一个执行就行,不用写一堆if-else,代码更简洁,以后要加新的出生边也方便扩展。

优化后代码

function calcEnemySpawnPos(r) {
  const spawnEdges = [
    // 左边出生
    () => ({ x: -r, y: getRandomInt(-r, canvas.height + r) }),
    // 右边出生
    () => ({ x: canvas.width + r, y: getRandomInt(-r, canvas.height + r) }),
    // 上边出生
    () => ({ x: getRandomInt(-r, canvas.width + r), y: -r }),
    // 下边出生
    () => ({ x: getRandomInt(-r, canvas.width + r), y: canvas.height + r })
  ];
  
  // 随机选一条边的生成逻辑
  const randomIndex = Math.floor(Math.random() * spawnEdges.length);
  return spawnEdges[randomIndex]();
}

可选扩展:支持自定义概率

如果之后需要调整各边的出生概率(比如想让左右边敌人更多),可以改成带权重的版本,灵活度更高:

function calcEnemySpawnPos(r) {
  // 每个项包含权重和生成函数,权重总和建议设为100方便计算
  const spawnOptions = [
    { weight: 25, spawn: () => ({ x: -r, y: getRandomInt(-r, canvas.height + r) }) },
    { weight: 25, spawn: () => ({ x: canvas.width + r, y: getRandomInt(-r, canvas.height + r) }) },
    { weight: 25, spawn: () => ({ x: getRandomInt(-r, canvas.width + r), y: -r }) },
    { weight: 25, spawn: () => ({ x: getRandomInt(-r, canvas.width + r), y: canvas.height + r }) }
  ];
  
  let roll = Math.random() * 100;
  for (const option of spawnOptions) {
    roll -= option.weight;
    if (roll <= 0) {
      return option.spawn();
    }
  }
  // 兜底返回最后一个,理论上不会走到这
  return spawnOptions.at(-1).spawn();
}

内容的提问来源于stack exchange,提问作者Ryan Peschel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 05:46:07