問題を正しく理解している場合、速度のランダムな方向を選択したいが、速度を変更したくない。これを行うには、x方向とy方向のランダム速度成分を選択し、各成分をベクトルの大きさで除算して単位ベクトルに正規化します。
また、math.random(-1, 1)
は-1,0または1の値しか与えません。方向をさらに多様にする場合は、math.random()
を使用して[0、1]の範囲の浮動小数点値を取得します。コンポーネントをネガティブにすることを無作為に選択して、完全な方向のスペクトルを得ることができます。ここで
はvx
とvy
速度成分のペアを返す少し機能である:ここでは
function rand_v_dir()
vx = math.random()
vy = math.random()
norm = math.sqrt(vx * vx + vy * vy)
vx = vx/norm
vy = vy/norm
if math.random(0, 1) == 0 then
vx = -vx
end
if math.random(0, 1) == 0 then
vy = -vy
end
return vx, vy
end
は、上記の関数によって生成された10のランダム速度ベクトルです:
> for i = 1, 10 do
vx, vy = rand_v_dir()
print("Velocity: ", vx, vy)
print("Speed: ", math.sqrt(vx * vx + vy * vy))
end
Velocity: -0.70784982398251 0.70636295676368
Speed: 1.0
Velocity: -0.28169296961382 -0.95950459658625
Speed: 1.0
Velocity: 0.71839382297246 -0.69563662577168
Speed: 1.0
Velocity: 0.29007205509751 0.9570048081653
Speed: 1.0
Velocity: -0.40540707321421 0.91413626171807
Speed: 1.0
Velocity: -0.7236198731718 0.69019872439091
Speed: 1.0
Velocity: 0.31888322750977 0.94779401096069
Speed: 1.0
Velocity: -0.64427423170525 0.76479455696325
Speed: 1.0
Velocity: -0.66481241135881 0.74701034644996
Speed: 1.0
Velocity: -0.65843036923729 0.75264164704463
Speed: 1.0
私たちはより良い行うことができますしかし、これよりも。このアプローチは、コメントに@JoelCornettと@nobodyと指摘されているように、コーナーに向かって偏った方向を与える。 1つの改善は、と2πの間のランダムな角度を選択し、速度ベクトルを単位ベクトルとすることです。角度の余弦はx方向の速度成分になり、角度の正弦はy方向の成分(正のx軸に対する角度を測定)になります。上記のアプローチの両方について
> for i = 1, 10 do
vx, vy = rand_polar_dir()
print("Velocity: ", vx, vy)
print("Speed: ", math.sqrt(vx * vx + vy * vy))
end
Velocity: 0.093304068605003 -0.99563766038743
Speed: 1.0
Velocity: -0.31453683190827 -0.9492452693446
Speed: 1.0
Velocity: 0.72403297094833 0.68976536371416
Speed: 1.0
Velocity: -0.39261186353618 -0.91970425931962
Speed: 1.0
Velocity: -0.74523744965918 0.66679917788303
Speed: 1.0
Velocity: 0.15192428057379 -0.98839213522374
Speed: 1.0
Velocity: 0.93666276755405 -0.35023257969239
Speed: 1.0
Velocity: 0.86478573695856 -0.50214104507902
Speed: 1.0
Velocity: 0.64665884247741 -0.7627793530542
Speed: 1.0
Velocity: 0.2877390096936 0.95770886092828
Speed: 1.0
、:ここ
function rand_polar_dir()
dir = 2 * math.pi * (math.random())
vx = math.cos(dir)
vy = math.sin(dir)
return vx, vy
end
は、第二のアプローチで生成10個のランダム速度ベクトルである:
このアプローチはまた、コードが簡単であるという利点を有します速度ベクトルの大きさは1です。速度を2倍にするには、ランダムベクトルに2を掛けます。
LÖVEを使用していますか? – Thelmund
速度は速度ベクトルのサイズに直接類似しています。 (2d)ベクトルのサイズは 'math.sqrt(Sprite.vx * Sprite.vy + Sprite.vy * Sprite.vy)'と定義されているので、スピードは可能な値の少数。*方向*をランダム化したいので、極座標で角度をランダムに選択し、その後に直交座標に変換することをお勧めします。 –