如何简化我的游戏敌人生成算法? (包括代码段)

时间:2018-08-08 15:07:29

标签: javascript

我在屏幕中间有一个英雄角色,我想以随机的位置在他周围生成僵尸,但要与他保持一定距离。 heroDistance定义了这个距离。

生成它们时,是否将它们推到屏幕边界之外并不重要,它们都会朝他走来。这是否发生并不重要,但看起来似乎更容易。

目前,使用random(screenWidth)和y轴random(screenHeight)为x轴创建了僵尸的随机位置,这些值被馈送到spawnLocation函数中,具体取决于位置它们相对于英雄而言有所增加或减少,以将其移开。

我的代码似乎太冗长,即使我为此付出了很多努力。我是否缺少使它更简单的显而易见的技术?

const state = {
  options: {
    numberOfZombies: 10,
  },
  characters: {
    hero: {
      xPosition: 150,
      yPosition: 150,
    },
  },
};

const screenWidth = 400;
const screenHeight = 400;

const random = range => Math.floor(Math.random() * range);

function createZombies(state) {
  const heroDistance = 10;
  const spawnLocation = (zomPos, heroPos, axisLength) => {
    return zomPos > heroPos
      ? zomPos + axisLength / heroDistance
      : zomPos - axisLength / heroDistance;
  };

  for (let index = 0; index < state.options.numberOfZombies; index += 1) {
    console.log({
      xPosition: spawnLocation(
        random(screenWidth),
        state.characters.hero.xPosition,
        screenWidth,
      ),
      yPosition: spawnLocation(
        random(screenHeight),
        state.characters.hero.yPosition,
        screenHeight,
      ),
    });
  }
}

createZombies(state);

1 个答案:

答案 0 :(得分:3)

生成一个随机的角度和半径,然后将这些值转换为笛卡尔坐标。

let theta = Math.random() * (2 * Math.PI)
let r = Math.random() * variationInR + minimumR

let zombieX = Math.cos(theta) * r + heroX
let zombieY = Math.sin(theta) * r + heroY

如果希望它们是整数,则使它们成为整数。这会从英雄至少minimumR个单位(毕达哥拉斯距离)以外的地方均匀地放射状产生僵尸。如果要保持曼哈顿距离行为,则生成dXdY并将其添加到英雄的位置。