随机生成 += 或 -= javascript

Randomly generate += or -= javascript

提问人:user3112634 提问时间:2/21/2022 更新时间:2/21/2022 访问量:58

问:

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

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;

提前致谢。

JavaScript 随机 变量 值赋值运算符

评论

3赞 2/21/2022
Math.floor(Math.random() * 2) * 2 - 1是 -1 或 1,只需乘以并将其添加到您的坐标中即可。pos

答:

2赞 machineghost 2/21/2022 #1

如果你想随机做,或者你可以简单地使用第一个版本,然后将你的值乘以如果你想做一个.x += valuex -= value-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;
1赞 Jean KOUSSAWO 2/21/2022 #2

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

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