こんにちは。
ピータンパン さんが書きました:お世話サマです!
プレイヤーの現在マップ座標の周囲48マスの中から
乱数で値を取得したいです!
でも、Math.random()の計算式がいまいちよく分かりません!
コード: 全て選択
var x = this.character(-1).x;
var y = this.character(-1).y;
($gameVariables.setValue(3,Math.floor( Math.random() * x)+6) + (x-6));
($gameVariables.setValue(4,Math.floor( Math.random() * y)+6) + (y-6));
プレイヤーの周囲48マスの中からランダムで座標を取得する方法をどうか教えてください!
乱数で指定した範囲の値を取りたい場合、Math.floor を使用する場合は、
コード: 全て選択
Math.floor(Math.random() * (最大値 + 1 - 最小値)) + 最小値
で取得することができるはずです。
±6というのであれば、
コード: 全て選択
Math.floor(Math.random() * ( 6 + 1 - (-6)) + (-6));
=
コード: 全て選択
Math.floor(Math.random() * 13) - 6)
となります。
なので、
コード: 全て選択
let x = this.character(-1).x;
let y = this.character(-1).y;
x = (x + Math.floor(Math.random() * 13) - 6).clamp(0, $gameMap.width() - 1);
y = (y + Math.floor(Math.random() * 13) - 6).clamp(0, $gameMap.height() - 1);
($gameVariables.setValue(3, x);
($gameVariables.setValue(4, y);
のように変更すれば、プレイヤーを中心に、上下左右6マス以内の座標を取得できると思います。
上記のコードでは、ついでにマップ範囲からはみ出さないように値を丸めています。
ご確認ください。