Unity mobile game Path & lt; 10 & gt; automatic searching for Navmesh jumps, climbs, slopes,

Source: Internet
Author: User

Unity mobile game Path <10> automatic search for Navmesh jumps, climbs, slopes,
Reprinted Unity mobile game road <10> automatic Pathfinder Navmesh jump, climb, Slope Classification: unity2013-12-27 6545 people read comments (5) collection reports unity3dNavmesh mobile game automatic Pathfinder

In the previous blogs, we have systematically learned the concepts and details of the automatic pathfinding plug-in Navmesh. However, if you want to make a mobile game with exquisite scenes, you need to use a variety of complex scene terrain, not just the automatic seek on the ground. Today, we will use a complete and complex instance to go through all the details. We will implement a complex scenario where the role can climb, jump, and climb. Does it feel like a csgame? Some basic animation functions will be used in this case. You can take a rough look at them in the document. This example is made from an official example.

(Reprinted please indicate the original address http://blog.csdn.net/janeky/article/details/17598113)

  • Procedure
1. Place various models in the scene, including floors, slopes, mountains, escalators, etc.
2. Add Navigation Static and OffMeshLink Generatic to all models (this is required, for example, if the floor is connected to the slope, you do not need to add OffMeshLink to the slope)
3. For special escalators, you must manually add the Off Mesh Link to set the start point and end point.
4. Save and bake scenarios
5. Add a role model and add the Nav Mesh Agent component to it.
6. Add a new script for the role, AgentLocomotion. cs, which is used to process automatic pathfinding and has been transformed by the role animation. The code is long and can be understood with comments.
[Csharp]View plaincopy
  1. Using UnityEngine; using System. collections; public class AgentLocomotion: MonoBehaviour {private Vector3 target; // target location private NavMeshAgent; private Animation anim; // Animation private string locoState = "Locomotion_Stand"; private Vector3 linkStart; // OffMeshLink start point private Vector3 linkEnd; // OffMeshLink end point private Quaternion linkRotate; // OffMeshLink rotation private bool begin; // start searching // Use this Initialization void Start () {agent = GetComponent <NavMeshAgent> (); // automatically moves and disables OffMeshLinks, that is, the OffMeshLink generated directly in two isolation obstacles. The agent does not automatically cross the agent. autoTraverseOffMeshLink = false; // create an animation AnimationSetup (); // start a coroutine to process the animation state machine StartCoroutine (AnimationStateMachine ();} void Update () {// click if (Input. getMouseButtonDown (0) {// Ray ray from the Camera to the click position = Camera. main. screenPointToRay (Input. mousePosition); RaycastHit h It; if (Physics. raycast (ray, out hit) {// determines whether the clicked terrain is if (hit. collider. tag. equals ("Obstacle") {begin = true; // click the position coordinate target = hit. point ;}}// for each frame, set the target point if (begin) {agent. setDestination (target) ;}} IEnumerator AnimationStateMachine () {// Processing Based on Different locoState states and calling the relevant function while (Application. isPlaying) {yield return StartCoroutine (locoState) ;}}// standing IEnumerator Locomotion_Stand () {do {UpdateAni MationBlend (); yield return new WaitForSeconds (0);} while (agent. remainingDistance = 0); // if the target point is not reached, go to the next status Locomotion_Move locoState = "Locomotion_Move"; yield return null;} IEnumerator Locomotion_Move () {do {Wait (); yield return new WaitForSeconds (0); // The role is in OffMeshLink. Select different animations if (agent) based on different locations. isOnOffMeshLink) {locoState = SelectLinkAnimation (); return (true) ;}} while (agent. RemainingDistance! = 0); // the target point has been reached, and the status changes to Stand locoState = "Locomotion_Stand"; yield return null;} IEnumerator Locomotion_Jump () {// play the Skip animation string linkAnim = "RunJump"; Vector3 posStart = transform. position; agent. stop (true); anim. crossFade (linkAnim, 0.1f, PlayMode. stopAll); transform. rotation = linkRotate; do {// calculate the new position float tlerp = anim [linkAnim]. normalizedTime; Vector3 newPos = Vector3.Lerp (posStart, linkEnd, tler P); newPos. y + = 0.4f * Mathf. sin (3.14159f * tlerp); transform. position = newPos; yield return new WaitForSeconds (0);} while (anim [linkAnim]. normalizedTime <1); // The animation is restored to Idle anim. play ("Idle"); agent. completeOffMeshLink (); agent. resume (); // The next status is Stand transform. position = linkEnd; locoState = "Locomotion_Stand"; yield return null;} // the center position of the ladder IEnumerator Locomotion_Ladder () {// Vector3 linkCent Er = (linkStart + linkEnd) * 0.5f; string linkAnim; // you can determine whether it is on a ladder or under a ladder if (transform. position. y> linkCenter. y) linkAnim = "Ladder Down"; else linkAnim = "Ladder Up"; agent. stop (true); Quaternion startRot = transform. rotation; Vector3 startPos = transform. position; float blendTime = 0.2f; float tblend = 0f; // The position interpolation change of the role (changes within 0.2) do {transform. position = Vector3.Lerp (startPos, linkStart, tblend/blendT Ime); transform. rotation = Quaternion. lerp (startRot, linkRotate, tblend/blendTime); yield return new WaitForSeconds (0); tblend + = Time. deltaTime;} while (tblend <blendTime); // sets the position transform. position = linkStart; // play the animation anim. crossFade (linkAnim, 0.1f, PlayMode. stopAll); agent. activateCurrentOffMeshLink (false); // wait until the animation ends do {yield return new WaitForSeconds (0);} while (anim [linkAnim]. normalizedT Ime <1); agent. activateCurrentOffMeshLink (true); // restore the Idle status anim. play ("Idle"); transform. position = linkEnd; agent. completeOffMeshLink (); agent. resume (); // The next status Stand locoState = "Locomotion_Stand"; yield return null;} private string SelectLinkAnimation () {// obtain the current OffMeshLink data OffMeshLinkData link = agent. currentOffMeshLinkData; // whether the computing role is currently at the start or end of the link (because OffMeshLink is bidirectional) float distS = (transfor M. position-link. startPos ). magnste; float distE = (transform. position-link. endPos ). magntables; if (distS <distE) {linkStart = link. startPos; linkEnd = link. endPos;} else {linkStart = link. endPos; linkEnd = link. startPos;} // Vector3 alignDir = linkEnd-linkStart in the direction of OffMeshLink; // ignore the Y axis alignDir. y = 0; // calculate the Rotation Angle linkRotate = Quaternion. lookRotation (alignDir); // determines whether the OffMeshLink is manually (STAIR) or automatically generated (hop If (link. linkType = OffMeshLinkType. linkTypeManual) {return ("Locomotion_Ladder");} else {return ("Locomotion_Jump") ;}} private void AnimationSetup () {anim = GetComponent <Animation> (); // place the walk and run animations on the same layer and synchronize their speed. Anim ["Walk"]. layer = 1; anim ["Run"]. layer = 1; anim. syncLayer (1); // set the Animation Mode and speed of "jump", "climb stairs", and "down stairs" anim ["RunJump"]. wrapMode = WrapMode. clampForever; anim ["RunJump"]. speed = 2; anim ["Ladder Up"]. wrapMode = WrapMode. clampForever; anim ["Ladder Up"]. speed = 2; anim ["Ladder Down"]. wrapMode = WrapMode. clampForever; anim ["Ladder Down"]. speed = 2; // initialize the animation status to Idle anim. crossFade ("Idle", 0.1f, PlayMode. stopAll);} // update the animation fusion private void UpdateAnimationBlend () {// walking speed float walkAnimationSpeed = 1.5f; // Running Speed float runAnimationSpeed = 4.0f; // speed threshold value (critical point of idle and walk) float speedThreshold = 0.1f; // speed, only x and z Vector3 velocityXZ = new Vector3 (agent. velocity. x, 0.0f, agent. velocity. z); // The speed value float speed = velocityXZ. magn#; // set the Run animation speed anim ["Run"]. speed = speed/runAnimationSpeed; // set the animation speed for a Walk. anim ["Walk"]. speed = speed/walkAnimationSpeed; // determine the playing status of the animation based on the agent speed. if (speed> (walkAnimationSpeed + runAnimationSpeed)/2) {anim. crossFade ("Run");} else if (speed> speedThreshold) {anim. crossFade ("Walk");} else {anim. crossFade ("Idle", 0.1f, PlayMode. stopAll );}}}

     

As shown in the following figure, the role can be automatically searched for at any location. The middle may go through different obstacles. We can see that the role can jump down, climb the stairs, and finally reach the target point, as we expected.


 

  • Summary

 

Today's example is complex. We need to process the role's actions based on the type of the pathfinding grid, such as common pathfinding, crawling, or jumping. This example is close to a real project. If you still have more complex paths in your project, you are welcome to discuss them. Ken@iamcoding.com

 

  • Source code

 

Http://pan.baidu.com/s/1i35cVOD

 

  • References
1. http://www.xuanyusong.com/
2. http://liweizhaolili.blog.163.com/
3. http://game.ceeger.com/Components/class-NavMeshAgent.html

Related Article

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.