There's a need in the work these days: Make the NPCs in the game go to a position in a non-linear way. When the character moves toward the target position, there is a certain shift in the left and right direction, but there is no deviation when reaching the target position. It is known that two two-dimensional coordinate points on the plane represent the starting and ending point, and the maximum offset range. When given a moment, you need to output the current position of the role.
The first thing I do is to draw the entire trajectory, using a software I wrote: A mathematical graphical visualizer that generates mathematical graphics using script code that defines its own syntax. The software is free to open source. QQ Exchange Group: 367752815
The script code is as follows:
vertices = +T= from(0) to (Ten*PI) s= sin (t) *sin (t/Ten) #起点与终点sx= Rand2 (-Ten,Ten) Sy= Rand2 (-Ten,Ten) Ex= Rand2 (-Ten,Ten) EY= Rand2 (-Ten,Ten) #宽度w=2DX= ex-Sxdy= EY-Sylen= sqrt (dx*dx + dy*dy) DirX= dx/Lendiry= Dy/len
Software:
After the graphic is drawn, you can make sure that the character walks in the diagram.
Finally write down the implementation code for C + +:
1 //An algorithm to achieve a target point of the NPC curve walking in the client2 voidCalculateposition (out vector2& pos,Constvector2& Vstart,Constvector2& Vend, unsignedintSin_count,floatWidthfloatt)3 {4 if(T <0.0f)5 {6pos =Vstart;7 return;8 }9 Else if(T >1.0f)Ten { Onepos =Vend; A return; - } - theVector2 vsub = Vend-Vstart; - floatLen = sqrtf (vsub.x*vsub.x + vsub.y*vsub.y); - if(Len <Flt_epsilon) - { +pos =Vstart; - return; + } A at floats = Width*sinf (m_pi*sin_count*t) *sinf (m_pi*t); - -Vector2 VDir = vsub/Len; - -Pos.x = Vstart.x + vsub.x*t-vdir.y*s; -Pos.y = vstart.y + vsub.y*t + vdir.x*s; in}
The algorithm of character curve walking in game