游戏中角色曲线行走的算法

      这几天工作中碰到一个需求:使游戏中的NPC角色以非直线的方式走到某一位置。角色在朝着目标位置移动时,有一定的左右偏移,但到达目标位置时不能有偏差。问题中已知的是平面上的两个二维坐标点表示起点与终点,最大的偏移范围。当给定一个时刻时,需要输出角色的当前位置。

      首先我做的是将整个行走轨迹画出来,这里使用我写的一个软件:数学图形可视化工具,使用自己定义语法的脚本代码生成数学图形。该软件免费开源.QQ交流群: 367752815

脚本代码如下:

vertices = 1000

t = from (0) to (10*PI)

s = sin(t)*sin(t/10)

#起点与终点
sx = rand2(-10, 10)
sy = rand2(-10, 10)
ex = rand2(-10, 10)
ey = rand2(-10, 10)

#宽度
w = 2

dx = ex - sx

dy = ey - sy

len = sqrt(dx*dx + dy*dy)
dirx = dx/len
diry = dy/len

软件截图:

图形画出后,可以确定使角色以图中轨迹行走。

最后写下C++的实现代码:

 1 // 实现客户端中NPC曲线行走到达某一目标点的算法
 2 void CalculatePosition(OUT Vector2& pos, const Vector2& vStart, const Vector2& vEnd, unsigned int sin_count, float width, float t)
 3 {
 4     if (t < 0.0f)
 5     {
 6         pos = vStart;
 7         return;
 8     }
 9     else if (t > 1.0f)
10     {
11         pos = vEnd;
12         return;
13     }
14 
15     Vector2 vSub = vEnd - vStart;
16     float len = sqrtf(vSub.x*vSub.x + vSub.y*vSub.y);
17     if (len < FLT_EPSILON)
18     {
19         pos = vStart;
20         return;
21     }
22 
23     float s = width*sinf(M_PI*sin_count*t)*sinf(M_PI*t);
24 
25     Vector2 vDir = vSub/len;
26 
27     pos.x = vStart.x + vSub.x*t - vDir.y*s;
28     pos.y = vStart.y + vSub.y*t + vDir.x*s;
29 }
原文地址:https://www.cnblogs.com/WhyEngine/p/4032971.html