Sunteți pe pagina 1din 4

A Pathfinding Algorithm in Real-time Strategy Game based on Unity3D

Jie Hu, Wang gen Wan, Xiaoqing Yu


School of Communication and Information Engineering, Shanghai University, Shanghai,
P.R.China
Institute of Smart City, Shanghai University, China
Shanghai HanPan Information S&T Ltd, Shanghai, China
E-mail: hujie20@hotmail.com

Abstract In the state space search, we can design an


evaluation function to decide every expansion in order
Pathfinding in the context of video games concerns to search for a given state space[5] more effectively and
the way in which a moving entity finds a path around find which node has the biggest change to reach the
obstacles; the most frequent context is real-time target node, then the searching will outward expansion
strategy games (in which the player directs units alone the considered most promising node. It will
around a play area containing obstacles), but forms of greatly reduce the search effort if we can give a more
this are found in most modern video games. It is appropriate valuation function. It is very important of
probably the most popular but frustrating game node valuation and the use of different valuation can
artificial intelligence (AI) problem in game industry. have different effects.
This article introduces A-Star algorithm first, then
describes the details of A-Star algorithm. Finally, a 3. A-Star algorithm
real example of how the A-Star pathfinding technique
is used in a famous 3D game engine: Unity3D. Heuristic search algorithm includes partial
merit-based search method, the best-first[6] search
1. Introduction method and so on. They all use a heuristic function, but
have different strategies in the selection of the best
In Artificial Intelligence field, A-Star algorithm is a search node. Such as partial merit-based[7] search
computer algorithm that is often used in pathfinding method which abandons the other sibling and father
and graph traversal, the process of finding ashortest node and keep searching in the process of selecting the
traversable path between points,called nodes.Because “best node”. Because of discarded other nodes which
of its advantage and performance, it has been may include the best node, solving the optimal node is
widelyused.In 1964 Nils Nilsson[1] invented a heuristic just the best at that stage, is not necessarily a global
based approach to increase the speed of Dijkstra's best. Best-First algorithm overcomes this shortfall, it
algorithm. This algorithm was called A1. In 1967 did not abandon the node (unless the node is a dead
Bertram Raphael made dramatic improvements upon node), in the searching and get a “best node” by
this algorithm, but failed to show optimality. He called comparing the estimated value between the current
this algorithm A2. Then in 1968 Peter E. Hart node and the last node in every step of valuation, can
introduced an argument that proved A2 was optimal effectively prevent the loss of “best node”.
when using a consistent heuristic with only minor A-Star algorithm is the best-first algorithm together
changes. His proof of the algorithm also included a with some constraints. When the state space is big, we
section that showed that the new A2 algorithm[2] was hope to solve the shortest path of the state space
the best algorithm possible given the conditions. He searching, that is the fastest way to solve the problem.
thus named the new algorithm in Kleene star syntax to A-Star algorithm is based on this idea.
be the algorithm that starts with A and includes all
possible version numbers or A*[3,4]. 3.1. Algorithm implementation and procedure

2. Heuristic algorithm Let’s assume that we want to get from point A to


point B and there is anobstacle separates the two

978-1-4673-0174-9/12/$31.00 ©2012 IEEE 1159 ICALIP2012


points. This is illustrated below, see Figure1.With As the figure shows, we divide the world into unit
green block represents the starting point A, and red cells. We measure the distance of moving straight up,
represents the ending point B, and the blue filled down, left or right as 1 unit and a diagonal move as 1.4
squares represents the obstacle between them. units. The diagonal of an unit square measures √2
which approximately equals 1.4. Because computer
operates faster with integers than floating point
numbers, so we multiply the unit distances by 10 to
obtains integer constants: 10 and 14. All distances
become 10 time longer than their actual distance but
still compare similarly when measures relative to each
other.
h(n) can be estimated in a variety of ways. The
standardmethod is Manhattan Method[7,8]. Its primary
advantage is that it will generally get you to the target
faster than most alternatives.The equation, where abs =
absolute value, is:
Figure 1.Search Area
h=10*(abs(currentX-targetX) +abs(currentY-targetY))
3.2. Start Searching
In this article, we use Diagonal Shortcut
Once we have simplified our search area into a
Method,balances h with g. Its primary advantage is that,
manageable number of nodes, as we have done with
because it is balanced, it is able to fully consider small
the grid layout above, the next step is to conduct a
modifiers like a turning penalty or influence map
search to find the shortest path. We do this by starting
modifier. It is also admissible. It is a bit slower than
at point A, checking the adjacent squares, and
the Manhattan method, though. The equation, where
generally searching outward until we reach our target.
abs = absolute value, is:
In Figure 2, the dark green square in the center is our
starting square. For each of adjacent squares, saves
point A as its parent square. This parent square stuff is xDistance = abs(currentX-targetX)
important when we want to trace our path. yDistance = abs(currentY-targetY)
if (xDistance>yDistance)
h = 14*yDistance + 10*(xDistance-yDistance)
else
h = 14*xDistance + 10*(yDistance-xDistance)
end if

f is calculated by adding g and h. The results of the


first step in our search can be seen in the Figure 3.

Figure 2.Father Node

3.3. Evaluation Function

The key to determining which squares to go when


figuring out the path is the following evaluation
function:
f n g n h n (1)
Where g(n) is the movement cost to move from the
starting point to a given square on the grid, following Figure 3.Path Scoring
the path generated to get there. h(n) is the estimated of
the cost of optimal path from node n to the target 3.4. Continuing the Search
square on the grid to the final destination, point B.

1160
In the implementation process of the algorithm, we We repeat this process until we add the target square
need s structure G, in which the current generated to the closed list, at which point it looks something like
search graph is displayed[8]. The table OPEN is used to the Figure 6.
store the generated and to be extended nodes. The table
CLOSED is applied to store the generated and
processed nodes. The following is the flow chart, see in
Figure 4.
Start

OPEN=(s), f=h, CLOSED=(), vector=(), i=1


i++, j=1

OPEN list is null? Exit, failure put node(i) into vector


Yes
No Yes

Select the node n which is the smallest f value without j‐‐ j==i+1
previous setting from the table OPEN and put in into No
table Closed, l=length of CLOSED, j=l
No

n is the target node? i==j‐1?


No
vector(i)=vector(j) Figure 6.The Path Calculated
Yes
No Yes
Expand node n, generate successor node m
Exit, success
Yes
4. Implementation in Unity3D
Create the point from successor node m to n

4.1. Introduction of Unity3d


g(m)=g(n)+k(n, m) Put node(i) into vector, i=j,
j=1

No
Unity3D is a game development tool developed by
m in OPEN? m in CLOSED?
No
Danish company called Unity Technologies. The
Yes Yes
specific features include an integrated editor,
put m into successor node
table of n
g(m)<g(n)?
No
cross-platform release, terrain editing, shaders, scripts,
Yes
networking, physics, version control features. It is an
integrated authoring tool for creating 3D video games
Modify node k to m in table CLOSED, modify the value of
successor g, f in table OPEN and CLOSED which add here to k

or other interactive content such as architectural


Resort the nodes from small to large in the OPEN
table according to f value visualizations or real-time 3D animations. Unity’s
Figure 4.Flow Chart of A* Algorithm development environment runs on Microsoft Windows
and Mac OS X, and the games is produces can be run
To continue the search, we simply choose the lowest on Windows, Mac, Xbox 360, PlayStation 3, Wii, ipad,
f score square from all those that are on the open list. iphone, as well as Android platform. It can also
We then do the following with the selected square: produce browser games that use the Unity web player
1.Drop it from the open list and add it to the closed list. plugin, supported on Mac and Windows but not Linux.
2. Check all of the adjacent squares. 3. If an adjacent Unity also has the ability to export games to Adobe’s
square is already on the open list, check to see if this Stage 3D functionality in flash, but certain features that
path to that square is a better one. See in Figure 5. the web player supports are not useable due to
limitation in Flash.

4.2. Experiment and Result

The central script of the A* Pathfinding Project is


the script 'astarpath.cs', it acts as a central hub for
everything else.In the AstarPath inspector we create all
graphs and adjust all settings.There should always be
one (always one, no more) astarpath.cs component in a
scene which uses pathfinding.
The second most important component is the
'Seeker.cs' component, a Seeker component should be
Figure 5.Continuing Searching attached to every GameObject which uses pathfinding
(e.g all AIs).The Seeker component handles path calls

1161
for one unit and post processes the paths. The Seeker References
isn't needed, but it makes pathfinding easier.
Lastly there are the modifier scripts [1] Hart, P. E.; Nilsson, N. J.; Raphael, B. “A Formal Basis
(e.gSimpleSmoothModifier.cs). Modifiers for the Heuristic Determination of Minimum Cost Paths”,
post-processes paths to smooth or simplify them, if a SIGART Newsletter 37: 28–29.
modifier is attached to the same GameObject as a [2] ALEXANDER NAREYEK. AI in Computer Games
Seeker it will post-process all paths that Seeker [OL].http://www.ai-center.com/publications/nareyek-acmque
handles.See Figure 7,8 ue04.pdf.
[3] RemcoStraatman, William van der Sterren, ArjenBeij,
Killzone’s AI: dynamic procedural combat tactics [OL],
http://www.cgf-ai.com/docs/straatman_remco_killzone_ai.pd
f.
[4]Andrew Lupponw. Hierarchal AI [OL].
http://www-cs-students.stanford.edu/~amitp/Articles/Hierarc
halAI.html.
[5] SUNShudong, LIN Mao, “The coordination path
planning of multiple moving robots based on GA”[J],
Automation Journal,2000, 26(5):672-676.
[6] Mahmoud Tarokh, “Hybrid Intelligent Path Planning
forArticulated Rovers in Rough Terrain”[Z], Fuzzy Sets and
Figure 7.The scene in Unity3D Systems, 2008,159(21):2927-2937.
[7]YE Tao, CHEN Haikui, YANG Guosheng, “a new
method ofGlobal robot navigation and obstacle avoidance in
Unknownenvironment” [J], Robot,2003,25(6):516-520.
[8] GAO Qingji, YU Yongsheng, HU Dandan, “feasible path
searchand optimization Based on an improved A *
algorithm”, ChinaCivil Aviation College Journal, 2005,23
(4): 42-44.

Figure 8.Run in Unity3D

5. Conclusions
A-Star algorithm is a classic algorithm in artificial
intelligence, which can be not only used in the shortest
path searching in game maps, but commonly in the
optimal state deduction in chess class game with
complex state-space. In this paper, it is applied in
searching the shortest path to reach the target ball by
the virtual human.

6. Acknowledgement
This work was supported in part by Shanghai’s Key
Discipline Development Program under Grant No.
J50104.NSFC (60873130, 60872115), Shanghai’s
Leading Academic Discipline Project of Shanghai
Municipal Education Committee (J50104), and
Shanghai University’s Graduate Student Innovative
Fund (No.SHUCX112120). Shanghai Torch Program
(No.1001H173400).

1162

S-ar putea să vă placă și