The algorithm of character curve walking in game

Source: Internet
Author: User
Tags sin

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.