* Pathfinding Project (Unity * pathfinding plugin) using tutorial

Source: Internet
Author: User

Unity4.6 later versions have built-in pathfinding AI, the previous article has introduced

Unity3d pathfinding function Introduction and project demonstration

However, for two years the project has been using a * pathfinding this plugin, so take the time to write down the simple use of this plugin.

Depending on the type of game, the plug-in function used may be different, I will only introduce the simplest, but also the use of the most simple pathfinding. Complex such as follow, dynamic, there are corresponding examples to learn.

I have never been to see ...

Transfer from Http://blog.csdn.net/huutu http://www.thisisgame.com.cn

The following is a dynamic diagram, with a * plugin, writing very little code can be done to find the way.


1. Create a scene

Add some cube as an obstacle obstacles in the scene, add a Capsule as the player, add a plane as the ground, and add a plane as a ramp test.



When creating a gameobject, rename a * To add a Star path Finder component.


2, edit the scene, specify obstacles

A * plugin, is based on the layer to determine the obstacles, so we have to Cubes as obstacles are set to obstacle this Layer.


Then give us the floor, set the layer to Ground, and both floors are

Transfer from Http://blog.csdn.net/huutu http://www.thisisgame.com.cn

3. Creating a road-finding grid

Select a *, in inspector, expand. View the following panel.


In

The black arrow refers to the width of the height, where the width of the height, refers to the number of squares. Here is a A * lattice pathfinding.

Adjust the width height to cover the entire plane.

The red Arrow refers to the top left, top right, bottom left, bottom right, center four points, select one of the points, you can adjust the location of this point.

With the center selected, click on the snap Size indicated by the blue arrow, which will automatically align to the center location.



Continue Setup.

The red box in the collision testing, is generated by the forbidden lattice.

Because our Cubes is an obstacle, select the Layer-obstacles in the Mask where Cubes is located.


The height testing in the yellow box is used to allow the Pathfinding node to be detected with the Ground, such as the need to detect heights when climbing.


When the settings are complete, click Scan to generate the search grid.

Transfer from Http://blog.csdn.net/huutu http://www.thisisgame.com.cn

4. Write pathfinding AI Code

After generating the pathfinding, we can use a A * to find the path in the code.

First add the Seeker component on the Player Capsule.

Then create a new script AStarPlayer.cs as the test code.


In the code, first we emit rays from the screen to locate the target position.

Then use Seeker to start generating the shortest path.

Seeker when the build path succeeds, the location of each node is saved in the list.

We read the position in the list in order, shift the player to the corresponding position, and complete the pathfinding.


Here's the full code:

Using unityengine;using system.collections;using Pathfinding;public class Astarplayer:monobehaviour {//target location;    Vector3 targetposition;    Seeker Seeker;    Charactercontroller Charactercontroller;     The calculated route;    Path path;     Moving speed;    float playermovespeed = 10f;    Current point int currentwaypoint = 0;    bool Stopmove = true;    Player Center Point;         float Playercentery = 1.0f;//Use this for initializationvoid Start () {seeker = getcomponent<seeker> ();    Playercentery = TRANSFORM.LOCALPOSITION.Y;}    Seek the end of the road;        public void Onpathcomplete (Path p) {Debug.Log ("Onpathcomplete error =" +p.error);            if (!p.error) {currentwaypoint = 0;            Path = p;        Stopmove = false; } for (int index = 0; index < path.vectorPath.Count; index++) {Debug.Log ("path.vectorpath[" +i        ndex+ "]=" +path.vectorpath[index]); }//update is called once per framevoid update () {if (Input.            Getmousebuttondown (0)) {Raycasthit hit; if (!            Physics.raycast (Camera.main.ScreenPointToRay (input.mouseposition), out hit, +)) {return;            } if (!hit.transform) {return;            } targetposition = hit.point;//new Vector3 (Hit.point.x, TRANSFORM.LOCALPOSITION.Y, hit.point.z);            Debug.Log ("targetposition=" + targetposition); Seeker.        Startpath (Transform.position, targetposition,onpathcomplete);        }} void Fixedupdate () {if (path = = NULL | | stopmove) {return;        }//calculates the direction based on the position of the player's current position and the next pathfinding point; Vector3 Currentwaypointv = new Vector3 (path.vectorpath[currentwaypoint].x, Path.vectorpath[currentwaypoint].y +        Playercentery, path.vectorpath[currentwaypoint].z);        Vector3 dir = (currentwaypointv-transform.position). normalized;        Calculate how much distance this frame will move toward dir; Dir *= playermovespeed * time.fixedDeltatime;        The calculation plus the displacement of this frame will not exceed the next node;        float offset = vector3.distance (transform.localposition, CURRENTWAYPOINTV);            if (offset < 0.1f) {transform.localposition = Currentwaypointv;            currentwaypoint++;                if (Currentwaypoint = = path.vectorPath.Count) {Stopmove = true;                Currentwaypoint = 0;            Path = NULL; }} else {if (Dir.magnitude > Offset) {Vector3 tmpV3 = Dir                * (Offset/dir.magnitude);                dir = tmpV3;                currentwaypoint++;                    if (Currentwaypoint = = path.vectorPath.Count) {Stopmove = true;                    Currentwaypoint = 0;                Path = NULL;        }} transform.localposition + = dir; }    }}

This is the easiest way to find it.


There are a number of examples in the example of a *.

The simplest way to find a script is to inherit Aipath directly.

Create a new script PlayerAI.cs inherit Aipath as a test

Using unityengine;using system.collections;using pathfinding.rvo;namespace pathfinding{[RequireComponent (typeof ( Seeker)] [Requirecomponent (typeof (Charactercontroller))] public class Playerai:aipath {/** Minimum vel        Ocity for moving */public float sleepvelocity = 0.4F;        /** speed relative to velocity with which to play animations */public float animationspeed = 0.2F;         /** Effect which'll be a instantiated when end of path is reached.        * \see ontargetreached * * Public gameobject endofpatheffect; Public new void Start () {//call start in base script (Aipath) base.        Start ();        }/** point for the last spawn of #endOfPathEffect */protected Vector3 lasttarget; public override void Ontargetreached () {if (Endofpatheffect! = null && vector3.distance (Tr.posi tion, Lasttarget) > 1) {gameobject.instantiate (EndofpatheffECT, tr.position, tr.rotation);            Lasttarget = tr.position;        }} public override Vector3 Getfeetposition () {return tr.position; } protected new void Update () {if (Input.getmousebuttondown (0)) {RAYC                Asthit hit; if (! Physics.raycast (Camera.main.ScreenPointToRay (input.mouseposition), out hit, +)) {Retu                Rn                } if (!hit.transform) {return;            } target.localposition = Hit.point;            }//get velocity in world-space Vector3 velocity; if (canmove) {//calculate desired velocity Vector3 dir = calculatevelocity (Getfe                Etposition ());         Rotate towards Targetdirection (filled in by calculatevelocity) Rotatetowards (targetdirection);       DIR.Y = 0; if (Dir.sqrmagnitude > Sleepvelocity * sleepvelocity) {//if the velocity is large en Ough, move} else {//otherwise, just stand still (this en                Sures gravity is applied) dir = Vector3.zero;                    } if (This.rvocontroller! = null) {rvocontroller.move (dir);                velocity = rvocontroller.velocity; } else if (Navcontroller! = null) {#if falsenavcontroller.simplemove                    (Getfeetposition (), dir); #endif velocity = Vector3.zero; } else if (Controller! = NULL) {controller.                        Simplemove (dir);                    velocity = controller.velocity; } else {                       Debug.logwarning ("No Navmeshcontroller or Charactercontroller attached to Gameobject");                    velocity = Vector3.zero;            }} else {velocity = Vector3.zero; }        }    }}

Less code, but not as intuitive as writing.


Two different scripts can be used to achieve the pathfinding effect.


Sample Project Package Download:

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








* Pathfinding Project (Unity * pathfinding plugin) using tutorial

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.