U3d_ artificial Intelligence [a] a * search algorithm _ AI

Source: Internet
Author: User
Tags abs
1. Main ideas:
First of all, find a way to find a point, a right point to go over, and then reach the demand for road.
 Here, there are 3 properties for each point: The F,G,H.H is the estimated consumption of the current point to reach the endpoint, which can be expressed in terms of distance, but here our calculation method is
/* *now and end are points, one is the current point, the other is the endpoint
* Therefore, the calculated distance here is the X difference of two points and the y difference and
* *
H = mathf.abs (now.x-end.x) + mathf.abs ( NOW.Y-END.Y);
And g represents the consumption of the starting point at the current point, can be represented by the distance from the starting point to the current point. But the calculation is one point at a time, so the value of G may change in the calculation, because the parent node may change, and we calculate the value of G in this algorithm:
Now. Parent is the
g=vector2.distance (new Vector2 (NOW.X,NOW.Y), New Vector2 (now) that gets to the current point. Parent.x,now. PARENT.Y)) +now. PARENT.G;
The final f=g+h;
2. Create Point Class
     This kind of representation point, also is the most basic point, seek the point of the road time.
Using System.Collections;
Using System.Collections.Generic;
Using Unityengine;

public class point{Public point

    Parent {get; set;}
    Public float F {get; set;}
    Public float G {get; set;}
    Public float H {get; set;}
    public int × {get; set;}
    public int y {get; set;}
    public bool Iswall {get; set;}
    public point (int x, int y, point parent=null)
    {
        this.x = x;
        This.y = y;
        parent = parent;
        Iswall = false;
    }
    <summary>
    ///Update parent node, G and F, value
    ///</summary>
    ///<param name= "parent" ></param >
    ///<param name= "G" ></param> public
    void Updateparent (point parent, float g)
    {
        parent = parent;
        g = g;
        F = G + H;
    }
}
3. Create the Astar class to realize the path finding
Using System.Collections;
Using System.Collections.Generic;

Using Unityengine;
        public class Astar:monobehaviour {//initialization void Start () {initmap ();
        Point start = map[2, 3];
        Point end = Map[6, 3];
        Findpath (start, end);
    Showpath (start, end);
    } Private Const int mapwith = 15;
    Private Const int Mapheigh = 15;

    Private point[,] map = new Point[mapwith, Mapheigh]; <summary>///Tectonic map///</summary> public void Initmap () {for (int x = 0; x < Mapwith; X + +) {for (int y = 0; y < Mapheigh; y++) {map[x, y] = new Point (x, y)
            ;
        } map[4, 2].iswall = true;
        Map[4, 3].iswall = true;
    Map[4, 4].iswall = true;  ///<summary>///Core seek///</summary>///<param name= "star" > Start point </param>/// <param name= "End" > Ending point </param> public void Findpath (Point star, point end) {list<point> openlist = new List<point> ()
        ;
        list<point> closelist = new list<point> ();
        Openlist.add (Star);
            while (Openlist.count > 0) {Point point = findminpointf (openlist);
            Openlist.remove (point);
            Closelist.add (point);

            list<point> surrounpoints = getsurroundpoints (point);
            Pointsfilter (surrounpoints, closelist); Iterate through all the points acquired and do the related processing foreach (point surroundpoint in surrounpoints) {if openlist. IndexOf (Surroundpoint) >-1) {//If the point is already on the start list, let's see if you want to update the G-value float NOWG = CALCG (Surroun

                    Dpoint, point); if (NOWG < SURROUNDPOINT.G) {//If the new G value is less than the original G value, the G value is updated Surroundpoint.updatepa
                    Rent (point, NOWG);
                }
                }else {//if the store no longer starts on the list, add the point to the start list and do the related construction processing surroundpoint.parent = points;

                    CALCF (surroundpoint, end);

                Openlist.add (Surroundpoint); 
            } if (Openlist.indexof (end) >-1) {//If an endpoint appears in the open list, end the loop break; {}}}///<summary>///calculates f value///</summary>///<param name= "Now" &

        gt; current dot </param>///<param name= "End" > Endpoint </param> private void CALCF Now.
        H = Mathf.abs (now.x-end.x) + mathf.abs (NOW.Y-END.Y); if (now). Parent!= null) {now. G = vector2.distance (New Vector2 (now.x, NOW.Y), New Vector2 (now. Parent.x, now. PARENT.Y)) + now.
        PARENT.G; } now. F = Now. H + now.
    G ///<summary>///Look for the point where F value is minimal in the open list///</summary>///<param name= "Openlist" ></param&
    Gt /// <returns></returns> Private Point findminpointf (list<point> openlist) {float F = float.
        MaxValue;
        Point temp = null; foreach (point point at Openlist) {if (point). F < f) {f = point.
                F
            temp = point;
    } return temp;
    ///<summary>///Get dots around point///</summary>///<param name= "points" ></param> <returns></returns> Private list<point> getsurroundpoints (Point point) {point U
        p = null, down = NULL, left = NULL, right = NULL;
        Point lu = null, RU = NULL, LD = NULL, RD = NULL;
        if (Point.y < mapHeigh-1) {up = Map[point.x, Point.y + 1];
        } if (Point.y > 0) {down = Map[point.x, point.y-1];
  } if (Point.x > 0) {left = map[point.x-1, Point.y];      } if (Point.x < mapWith-1) {right = Map[point.x + 1, point.y];
        } if (up!= null && left!= null) {lu = map[point.x-1, Point.y + 1];
        } if (up!= null && right!= null) {RU = map[point.x + 1, Point.y + 1];
        } if (down!= null && left!= null) {ld = map[point.x-1, point.y-1];
        } if (down!= null && right!= null) {rd = Map[point.x + 1, point.y-1];
        } list<point> List = new list<point> (); if (down!= null && Down.iswall = = false) {list.
        ADD (down); } if (up!= null && Up.iswall = = false) {list.
        ADD (UP); } if (left!= null && Left.iswall = = false) {list.
        ADD (left); } if (right!= null && right.isWall = = false) {list.
        ADD (right);
        } if (Lu!= null && Lu.iswall = False && Left.iswall = False && Up.iswall = = False) {list.
        ADD (LU);
        } if (ld!= null && Ld.iswall = False && Left.iswall = False && Down.iswall = = False) {list.
        ADD (LD);
        } if (ru!= null && Ru.iswall = False && Right.iswall = False && Up.iswall = = False) {list.
        ADD (RU);
        } if (rd!= null && Rd.iswall = False && Right.iswall = False && Down.iswall = = False) {list.
        Add (RD);
    } return list; ///<summary>///filter out the points on the close list///</summary>///<param name= "Now" ></param>/
    <param name= ' close ' ></param> private void Pointsfilter (list<point> now, list<point> close)

      {  foreach (point to close) {if (now). IndexOf (point) >-1) {now.
            Remove (point); }}///<summary>///calculates the G value of the now point and returns///</summary>///<param name= "Now" &GT;&L t;/param>///<param name= "parent" ></param>///<returns></returns> Private float C ALCG (Point today, point parent) {return vector2.distance (new Vector2 (now.x, NOW.Y), New Vector2 (Parent.x, Pare NT.Y) + parent.
    G ///<summary>///Show path///</summary>///<param name= "star" ></param>///&L

        T;param name= ' end ' ></param> public void Showpath (Point star, point end) {Point temp = end;
            Draw path while (true) {Color c = color.gray;
            if (temp = = Star) {c = Color.green;
    else if (temp = = end) {            c = color.red;
            } createcube (temp.x, TEMP.Y, C); if (temp.
            Parent = = null) break; temp = temp.
        Parent;
            //Draw obstacles for (int x = 0; x < Mapwith + +) {for (int y = 0; y < Mapheigh; y++)
                {if (map[x, Y].iswall) {createcube (x, y, Color.Blue); ///<summary>///Select locations to create a square///</summary>/// <param name= "x" ></param>///<param name= "y" ></param>///<param name= "color" > Cube color &
        lt;/param> private void Createcube (int x, int y, color color) {print ("Createcube"); Gameobject go = gameobject.createprimitive (primitivetype.cube);//create Geometry go.transform.position = new Vector3 (x, y, 0
        ); Go.
    Getcomponent<renderer> (). Material.color = color;
 }
}
 Here is more important is the core algorithm, I also focus on to take a look: First is to create two lists openlist and Closelist, is used to store the points that need to check, and do not need to check the point, such as starting point, from the beginning to join the Closelist close list,
The findminpointf () is then used to get to the point around it, filtered and added to the open list for checking.
Loop through the retrieved points to check, if the point is already on the start list, and then see if you want to update the G value, update the G value if the new G value is less than the original G value, and if the point is no longer on the start list, add the point to the start list and do the related construction processing. So repeatedly add new points into the open list, the scope will slowly expand, and each point will have its parent node, when the end to enter the open list when the end of the loop, the same end also has a parent node, the parent node also has a parent node, until the parent node is empty, that is, the starting point, so there is a point from the end point to the beginning of the
The shortest path is obtained according to this method. 
    <summary>///Core Search///</summary>///<param name= "star" > Starting point </param>///& Lt;param name= "End" > Endpoint </param> public void Findpath (Point star, point end) {list<point> O
        Penlist = new list<point> ();
        list<point> closelist = new list<point> ();
        Openlist.add (Star);
            while (Openlist.count > 0) {Point point = findminpointf (openlist);
            Openlist.remove (point);
            Closelist.add (point);

            list<point> surrounpoints = getsurroundpoints (point);
            Pointsfilter (surrounpoints, closelist); Iterate through all the points acquired and do the related processing foreach (point surroundpoint in surrounpoints) {if openlist. IndexOf (Surroundpoint) >-1) {//If the point is already on the start list, let's see if you want to update the G-value float NOWG = CALCG (Surroun

                    Dpoint, point);
           if (NOWG < SURROUNDPOINT.G)         {//If the new G value is less than the original G value, update the G-Value surroundpoint.updateparent (point, NOWG); } else {//if the store no longer starts the list, add the point to the start list and do the related construction surround
                    Point.parent = point;

                    CALCF (surroundpoint, end);

                Openlist.add (Surroundpoint); 
            } if (Openlist.indexof (end) >-1) {//If an endpoint appears in the open list, end the loop break; }
        }
    }

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.