These slides are part of a course about interactive objects in games. The lectures cover some of the most widely used methodologies that allow smart objects and non-player characters (NPCs) to exhibit autonomy and flexible behavior through various forms of decision making, including techniques for pathfinding, reactive behavior through automata and processes, and goal-oriented action planning. More information can be found here: http://tinyurl.com/sv-intobj-2013
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
Pathfinding - Part 2: Examples in Unity
1. INTERACTIVE OBJECTS IN
GAMING APPLICATIONS
Basic principles and practical scenarios in Unity
June 2013Stavros Vassos Sapienza University of Rome, DIAG, Italy vassos@dis.uniroma1.it
2. Interactive objects in games
2
Pathfinding
Part 1: A* heuristic search on a grid
Part 2: Examples in Unity
Part 3: Beyond the basics
Action-based decision making
AI Architectures
4. Pathfinding: Examples in Unity
4
We will use a sample project in Pathfinding.zip
Based on
Aron Granberg A* Pathfinding project (free version)
http://arongranberg.com/astar/download
http://arongranberg.com/astar/docs/getstarted.php
3D Platformer Tutorial by Unity (free)
http://u3d.as/content/unity-technologies/3d-platformer-
tutorial/
Unzip, open project, and load scene “Pathfinding on
a plane” (it is already ready for experimentation)
5. Pathfinding: Examples in Unity
5
We will use a sample project in Pathfinding.zip
Based on
Aron Granberg A* Pathfinding project (free version)
http://arongranberg.com/astar/download
http://arongranberg.com/astar/docs/getstarted.php
3D Platformer Tutorial by Unity (free)
http://u3d.as/content/unity-technologies/3d-platformer-
tutorial/
Unzip, open project, and load scene “Pathfinding on
a plane” (it is already ready for experimentation)
Many other packages available, paid, free, or
freemium. You can also write your own!
6. Pathfinding: Examples in Unity
6
Creating the scene
Simple plane
Rigid body (docs.unity3d.com:Rigidbody)
Box collider (docs.unity3d.com:BoxCollider)
Checkerboard material
Crates
Rigid body
Box collider
Some material that looks nice
7. Pathfinding: Examples in Unity
7
Creating the scene
Simple plane
Rigid body (docs.unity3d.com:Rigidbody)
Box collider (docs.unity3d.com:BoxCollider)
Checkerboard material
We want to note that this is the “ground” for navigation
Crates
Rigid body
Box collider
Some material that looks nice
We want to note that these are “obstacles” for navigation
8. Pathfinding: Examples in Unity
8
Tags: mostly for finding game objects
(docs.unity3d.com:Tags)
Layers: mostly for rendering purposes
(docs.unity3d.com:Layers)
9. Pathfinding: Examples in Unity
9
Here we specify two layers
Ground
Obstacles
And set the plane and crates to
the correct one
10. Pathfinding: Examples in Unity
10
Creating the scene
Adding a character that we will instruct to move around
Lerpz prefab from 3D Platformer Tutorial of Unity
Character controller component
11. Pathfinding: Examples in Unity
11
Essentially a capsule-shaped Collider
(docs.unity3d.com:CharacterController)
Can be told to move in some direction from a script
Can carry out the movement but be constrained by
collisions (also step offset, slope limit)
12. Pathfinding: Examples in Unity
12
Aron’s pathfinding package
Adding pathfinding functionality in the scene
Create empty object
Name it “A* Pathfinder”
Add the AstarPath script from Aron’s package
This is a unique central hub for computing paths
Adding pathfiding functionality to the character
Add the Seeker component
13. Pathfinding: Ex. in Unity
13
Specify the parameters of the
AstarPath script
Grid Graph
Position/size
4-connected/8-connected
Cut corners
Collision testing
Type/size of collider
Mask: Use Obstacle Layer
Scan and observe!
14. Pathfinding: Ex. in Unity
14
Capsule collider with diameter 2
8-connected
15. Pathfinding: Ex. in Unity
15
Capsule collider with diameter 2
8-connected
“Cut corners”
option affects
these edges
16. Pathfinding: Ex. in Unity
16
Capsule collider with diameter 6
4-connected
17. Pathfinding: Examples in Unity
17
Using the Seeker script to get paths for Lerpz
Astar AI1
Astar AI2
Astar AI3
Astar AI4
Based on sample code in Aron’s pathfinding package
18. Pathfinding: Examples in Unity
18
Using the Seeker script to get paths for Lerpz
public class AstarAI1 : MonoBehaviour {
public Vector3 targetPosition;
public void Start () {
//Get a reference to the Seeker component
Seeker seeker = GetComponent<Seeker>();
//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 ("Yey, we got a path back!");
}
}
19. Pathfinding: Examples in Unity
19
Astar A1 script calls the Seeker's StartPath function
The Seeker creates a new Path instance and sends it to
the AstarPath script (in the A* Pathfinder game-object)
AstarPath script puts the path in a queue, when
available, it processes the path by searching the grid in
the A* heuristic search manner we described earlier
AstarPAth script calls the function OnPathComplete with
the path it found as a parameter p
p.VectorPath holds a list of Vector3 objects that show
how the destination can be reached
22. Pathfinding: Examples in Unity
22
Using Astar AI1 script, Lerpz is able to find out how
to get to the target object (fuel cell prefab)
So, let’s make Lerpz move!
Accessing other components
(docs.unity3d.com:Accessing)
SimpleMove function of Character component
(docs.unity3d.com:CharacterController.SimpleMove)
FixedUpdate instead Update for physics-related things
(docs.unity3d.com:FixedUpdate,
unity3d.com/tutorials:Update-and-Fixedupdate)
23. Pathfinding: Examples in Unity
23
public class AstarAI2 : MonoBehaviour {
...
//The calculated path
public Path path;
//The character’s speed
public float speed = 100;
//The distance to a waypoint for moving to the next
public float nextWaypointDistance = 3;
//The waypoint we are currently moving towards
private int currentWaypoint = 0;
public void Start () {
... }
public void OnPathComplete (Path p) {
... }
public void FixedUpdate () {
... }
}
24. Pathfinding: Examples in Unity
24
public class AstarAI2 : MonoBehaviour {
public void FixedUpdate () {
//Check if we reached the destination
if (currentWaypoint >= path.vectorPath.Count) {
Debug.Log ("End Of Path Reached");
return;
}
//Direction to the next waypoint
Vector3 dir = (path.vectorPath[currentWaypoint]-
transform.position).normalized;
dir *= speed * Time.fixedDeltaTime;
controller.SimpleMove (dir);
//Check if we need to switch to the next waypoint
if (Vector3.Distance(transform.position,
path.vectorPath[currentWaypoint]) < nextWaypointDistance) {
currentWaypoint++;
return;
}
}
25. Pathfinding: Examples in Unity
25
Lerpz moves but without animating its parts
Basic animation of pre-defined clips
Animation component (docs.unity3d.com:Animation)
Play(“walk”), Stop()
26. Pathfinding: Examples in Unity
26
Lerpz.fbx
Embedded animations that have
been created outside of Unity for
the 3D model
Available for
Playing
Looping
Blending
27. Pathfinding: Examples in Unity
27
public class AstarAI3 : MonoBehaviour {
...
//Cashed reference to Animation component
public Animation anim;
public void Start () { ...
anim = transform.GetComponentInChildren<Animation>();
}
public void OnPathComplete (Path p) { ...
anim.Play("walk");
}
public void FixedUpdate () { ...
if (currentWaypoint >= path.vectorPath.Count) {
Debug.Log ("End Of Path Reached");
anim.Stop();
return;
...
}
}
}
28. Pathfinding: Examples in Unity
28
We can do better than that!
Turn when changing direction while moving
Slow down before reaching destination
Nicer/smoother paths
Plan/replan for a moving target
Plan/replan with a dynamic grid
29. Pathfinding: Examples in Unity
29
We can do better than that!
Astar AI4 script
Target is a transform of an object in the game-world
Repath rate
Turning speed
Slowdown distance
Fancy code with coroutines and yield
(docs.unity3d.com:Coroutines-Yield)
30. Pathfinding: Examples in Unity
30
We can do better than that!
TargetMover script attached on main camera
Moves target to position of mouse
Always on or only when double click is detected
Use the fuel cell as a target
ObjectPlacer script attached on main camera
Pressing “p” adds a game-object instance at ray collision
with a game-object in the scene
Use it to place crates
Pressing “r” removes game-object
31. Pathfinding: Examples in Unity
31
public class TargetMover : MonoBehaviour {
...
//Handle continuous move in Update() function
void Update () {
if (!onlyOnDoubleClick && cam != null) {
UpdateTargetPosition ();
}
}
public void UpdateTargetPosition () {
//Define a ray from eye to mouse position
Ray ray = cam.ScreenPointToRay (Input.mousePosition);
//Do raycast and if it hits the given mask layer
RaycastHit hit;
if (Physics.Raycast(ray, out hit, Mathf.Infinity, mask)){
//transport the target at the hit position
target.position = hit.point;
}
}
32. Pathfinding: Examples in Unity
32
public class ObjectPlacer : MonoBehaviour {
...
void Update () {
if (Input.GetKeyDown ("p")) {
PlaceObject ();
}
if (Input.GetKeyDown ("r")) {
RemoveObject ();
}
public void PlaceObject () {
//Cast a ray, etc
...
}
public void RemoveObject () {
//Cast a ray, etc
...
}
}
33. Pathfinding: Examples in Unity
33
Scripts
Astar AI1
Astar AI2
Astar AI3
Astar AI4
TargetMover
ObjectPlacer
Either as originally from Aron’s Pathfinding Project or
with slight modifications
Use the ones in the project in Pathfinding.zip
36. Pathfinding: Examples in Unity
36
public void PlaceObject () {
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
//If we hit an object
if ( Physics.Raycast (ray, out hit, Mathf.Infinity)) {
Vector3 p = hit.point;
//Instantiate a new game-object
GameObject obj = (GameObject)GameObject.Instantiate
(go,p,Quaternion.identity);
//Update the pathfinding graph
Bounds b = obj.collider.bounds;
GraphUpdateObject guo = new GraphUpdateObject(b);
AstarPath.active.UpdateGraphs (guo);
}
}
37. Pathfinding: Examples in Unity
37
Local updates are faster if we have a huge map
But can be problematic when objects end up farther
away or may fall on the ground later than the update
46. Pathfinding Part 3: Beyond the basics
46
Many neat tricks for efficient/nice pathfinding
Alternative game-world representations
Beyond A*
Better heuristics