[Unity3d Plug-in series]-a* pathfinding Project Learning (i)

Source: Internet
Author: User

Always wanted to use the Unity3d homing module in the demo, but encountered some problems:

Requirements in the game to require the object can be found on the road, and become a barrier to other objects, I have added navmeshagent and navmeshobstacle on the same object, but the object of the abnormal situation, check the official documents and forums, There is no clear solution to this situation where it is added and functioning at the same time, but only to other pathfinding plugins, A * pathfinding project looks good, consider learning.

1. Scenario Preparation

Create a scene first

Add a plane so that its coordinates are in (0,0,0) and the three-way scale is 10

Add a new layer named ground and set the plane above as the ground layer

Add a few boxes as obstacles on the plane, add a new layer, name it obstacles, and place these boxes in the obstacles layer.

2. Add a *

Create an empty Gameobject, named a A *, and add the plug-in script Astarpath from the Components–>pathfinding–>pathfinder. You can see that it is divided into several parts in the Astarpath Observer, the most important of which is the graphs area and the bottom scan area, and the graphs area preserves all the pathfinding in the project, up to 16, but generally 1 to 2 are sufficient. There are several types of pathfinding, the main of which are two: Grid Pattern graph and Navmesh graph.

Add the grid graph first.

As stated in the name, grid graph produces a series of meshes with width * height, which can be placed anywhere in the scene or rotated. The node size sets the size of the space occupied by the node, which is set to 1, the right side has a small selection of 5 points, select the lower left corner of the point, set its coordinates (-50, 0.1, 50), Where the Y-direction is set to 0.1 to avoid floating-point errors, because the y-coordinate of the ground plane is 0, and if the navigation grid is also y to 0, it can cause problems when the raycast of the height detection is performed.

Height test:

In order to place the Pathfinding node in the correct position in the scene, it is generally used to fire a ray from node down to detect that the pathfinding node is placed in the location of the collision point. We set the mask to ground because we only want the pathfinding node to be detected with ground.

Crash test:

When the pathfinding node is placed, it is used to detect whether it is feasible to walk, and it is generally possible to use sphere,capsule or Ray for collision detection. The general capsule uses the same radius and height as the AI object to collide. To make the AI object and the obstacle have some edges, set the radius of the capsule to 2. Additionally, the layer of collision detection is set to obstacles because you do not want the ground to be an obstacle.

OK, all ready, click Scan at the bottom, we can see the generation of the grid graph, you can re-edit the window to see the Guide line display of the search grid, including the Pathfinding area and the barrier area.

3. Join the AI

These are the basic settings related to the scene pathfinding, and the next step is to join the AI object to find the path. Add a capsule to the scene and add a character controller component to it, adding seeker scripts from components–>pathfinding. The Seeker script is a helper class script that handles pathfinding requests from other scripts, and it can also handle path modifier (typically a script for smoothing the pathfinding results). A * Pathfinding project comes with two AI scripts to hook up to the object for pathfinding: Aipah can be applied to any type of pathfinding, whereas Richai only works with Navmesh types.

Using unityengine;using system.collections;//note This line, if it was left out, the script won ' t know that the class ' Path ' exists and it'll throw compiler errors//this line should always be present at the top of the scripts which use pathfinding    Using Pathfinding;public class astarai:monobehaviour{//the Point-to-move-to-public Vector3 targetposition;    Private Seeker Seeker;    Private Charactercontroller Controller;    The calculated path public path path;    The AI ' s speed per second public float speed = 200; The max distance from the AI to a waypoint for it to continue to the next waypoint public float nextwaypointdistance    = 3;    The waypoint we are currently moving towards private int currentwaypoint = 0;        public void Start () {seeker = getcomponent<seeker> ();        Controller = getcomponent<charactercontroller> (); Start a new path to the targetposition, return the result to the Onpathcomplete function//seekeR.startpath (Transform.position, targetposition, Onpathcomplete); } public void Onpathcomplete (path p) {Debug.Log ("Yay, we got a Path back. Did it has an error?        "+ P.error);            if (!p.error) {path = P;        Reset the waypoint counter currentwaypoint = 0;             }} void Update () {//See if user pressed the mouse down if (input.getmousebuttondown (0)) {            We need to actually hits an object raycasthit hits; if (!            Physics.raycast (Camera.main.ScreenPointToRay (input.mouseposition), out hit, +) return;            We need to hits something (with a collider on it) if (!hit.transform) return;            Get input vector from Kayboard or analog stick and make it length 1 at most targetposition = Hit.point; Seeker.        Startpath (Transform.position, targetposition); }} public void Fixedupdate () {       if (path = = null) {//we has no path to move after yet return;            } if (Currentwaypoint >= path.vectorPath.Count) {Debug.Log ("End of Path reached");        Return }//direction to the next waypoint Vector3 dir = (Path.vectorpath[currentwaypoint]-transform.position). Nor        malized;        Dir *= speed * time.fixeddeltatime; Controller.        Simplemove (dir); Check If we are close enough to the next waypoint//if we is, proceed to follow the next waypoint if (Vec Tor3. Distance (Transform.position, Path.vectorpath[currentwaypoint]) < nextwaypointdistance) {Currentwaypo            int++;        Return }    }}

This is a mouse-click Scene, and then the AI object is the script that seeks the path. If you feel that the route is not yet smooth, you can add a modification script for the pathfinding results in the components–>pathfinding–>modifier.

Well, this tutorial is over.

Conclusion: Although done in accordance with this tutorial, but found that some obstacles to the AI object will be stalled, but if it comes with its own aipah there is no problem.


[Unity3d Plug-in series]-a* pathfinding Project Learning (i)

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.