随机生成 += 或 -= javascript

Randomly generate += or -= javascript

您好,我正在尝试将 += 或 -= 分配给对象位置。 首先我有随机数学选择一个数字:

var min = 9;
 var max = 11;
 var pos = Math.floor(Math.random() * (max - min + 1)) + min;

我正在尝试将 pos 的输出添加到 this._target.position.z 和 this._target.position.x 但我希望它是随机添加或减去的

所以 Z 位置的随机输出应该是:

this._target.position.z += pos;

this._target.position.z -= pos;

然后对于 X 位置应该是:

this._target.position.x += pos;

this._target.position.x -= pos;

提前致谢。

如果你想随机做 x += valuex -= value 你可以简单地使用第一个版本,如果你想做 [=15] 然后将你的值乘以 -1 =].

换句话说:

const isNegative = // however you determine this, eg. Math.random
const newValue += (isNegative ? -1 : 1) * value;

或者,在评论中使用@Chris G 的建议,将其应用到您的案例中:

 const oneOrNegativeOne = (Math.floor(Math.random() * 2) * 2 - 1);
 this._target.position.x += oneOrNegativeOne * pos;

您可以使用基于随机事件的条件,如下所示:

if (Math.floor(Math.random() * 2)) {
    //the condition return 0 or 1 for false or true
    this._target.position.z += pos;
} else {
    this._target.position.z -= pos;
}

以及 this._target.position.x