如何引用随机生成的x和y值推入数组

时间:2018-08-05 11:28:47

标签: javascript arrays constructor

当将它们推入数组时,如何引用随机生成的X和Y值。在我的代码中:ax和ay数字是随机生成的值,我想在以后的阶段中引用它们并在循环中使用。我将生成许多对象,并且希望在计算中使用每个单独的ax和ay。目前,系统仅使用生成的第一个值或最后一个值。我有点菜鸟,感谢指导。

function create() {
  ax = Math.random() * width;
  ay = Math.random() * height;

  asteroids.push(new gameObject("asteroid", 0, 0, 0, 0, "asteroid11.png", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ax, ay, 250, 240, 0, 120, 1, 0, 0))
  guns.push(new gameObject("g", 0, 0, 0, 0, "gun3.png", 0, 0, ax + 125 - 67, ay - 23, 138, 78, 0, 0, 72, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
  bullets.push(new gameObject("b", ax + 125 - 67 + 138 / 2 - 14, ay - 23 + 78 / 2 - 15, 25, 25, "ball.png", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
}

1 个答案:

答案 0 :(得分:0)

一个简单的解决方案是从ax返回aycreate

function create() {
  ax = Math.random() * width;
  ay = Math.random() * height;

  asteroids.push(new gameObject("asteroid", 0, 0, 0, 0, "asteroid11.png", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ax, ay, 250, 240, 0, 120, 1, 0, 0))
  guns.push(new gameObject("g", 0, 0, 0, 0, "gun3.png", 0, 0, ax + 125 - 67, ay - 23, 138, 78, 0, 0, 72, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
  bullets.push(new gameObject("b", ax + 125 - 67 + 138 / 2 - 14, ay - 23 + 78 / 2 - 15, 25, 25, "ball.png", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));

  return [ax, ay];
}

这不是很清楚。更好的方法是将随机宽度和高度生成重构为独立函数:

const randomWidth = () => Math.random() * width;
const randomHeight = () => Math.random() * height;
const create = (ax, ay) => {

  asteroids.push(new gameObject("asteroid", 0, 0, 0, 0, "asteroid11.png", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ax, ay, 250, 240, 0, 120, 1, 0, 0))
  guns.push(new gameObject("g", 0, 0, 0, 0, "gun3.png", 0, 0, ax + 125 - 67, ay - 23, 138, 78, 0, 0, 72, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
  bullets.push(new gameObject("b", ax + 125 - 67 + 138 / 2 - 14, ay - 23 + 78 / 2 - 15, 25, 25, "ball.png", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));

};

// in your loop

for (/* ... */) {
    const ax = randomWidth();
    const ay = randomHeight():

    create(ax, ay);

    // do something with `ax` and `ay`
}