我有一个想要随机运动的游戏。我写了一种算法,该算法应该计算移动的方向和距离。这些目的地是圆周上的点。想象一下角色总是在这个圆圈的中间。为了使方向更改更平滑,我认为每个方向更改都应取决于前一个方向。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace randomwalk
{
class Program
{
static void Main(string[] args)
{
int? previousAngle = null;
while (true)
{
var angle = 0;
Random rnd;
if (previousAngle.HasValue)
{
rnd = new Random();
var shift = 10;
angle = previousAngle.Value + rnd.Next(shift) - shift/2;
if (angle > 359)
angle -= 180;
}
else
{
rnd = new Random();
angle = rnd.Next(359);
}
var radius = 160;
var x = Convert.ToInt32(Math.Cos(angle) * radius);
var y = Convert.ToInt32(Math.Sin(angle) * radius);
Console.WriteLine("Moved to: X:{0}, Y:{1}", x, y);
previousAngle = angle;
Thread.Sleep(1000);
}
}
}
}
问题是我没有得到预期的结果。此处的每次迭代都应以0-10之间的随机数进行角度转换。在实际结果中,角度变化远超过10度,甚至感觉完全是随机的。
Actual results:
Moved to: X:5, Y:160
Moved to: X:18, Y:-159
Moved to: X:143, Y:-71
Moved to: X:109, Y:117
Moved to: X:109, Y:117
我还想知道如何改善这一点,以及是否已有可以使用的运动算法,也许比这更好?
答案 0 :(得分:4)
如果我错了,请纠正我,但是您当前在调用Math.Cos
和Math.Sin
框架函数时正在使用度数。
这些函数希望输入参数位于radians
中。
有一种简单的转换算法,可以将度数转换为弧度,形式为(如MSDN上的链接主题所示):
double angle = Math.PI * degrees / 180.0;
具有这些功能至少应能对此更改进行纠正,我并未真正验证其余代码或它的假设:)
您可以在下面的dotnetfiddle中看到输出的变化,其输出类似于:
Moved to: X:73, Y:143
Moved to: X:82, Y:137
Moved to: X:92, Y:131
Moved to: X:101, Y:124
Moved to: X:109, Y:117
Moved to: X:117, Y:109
Moved to: X:124, Y:101
Moved to: X:131, Y:92
Moved to: X:137, Y:82