Pathfinding - Part 2: Examples in Unity

3,160 views

Published on

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

0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
3,160
On SlideShare
0
From Embeds
0
Number of Embeds
4
Actions
Shares
0
Downloads
60
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Pathfinding - Part 2: Examples in Unity

  1. 1. INTERACTIVE OBJECTS INGAMING APPLICATIONSBasic principles and practical scenarios in UnityJune 2013Stavros Vassos Sapienza University of Rome, DIAG, Italy vassos@dis.uniroma1.it
  2. 2. Interactive objects in games2 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
  3. 3. Pathfinding: Examples in Unity3
  4. 4. Pathfinding: Examples in Unity4 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 ona plane” (it is already ready for experimentation)
  5. 5. Pathfinding: Examples in Unity5 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 ona plane” (it is already ready for experimentation)Many other packages available, paid, free, orfreemium. You can also write your own!
  6. 6. Pathfinding: Examples in Unity6 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. 7. Pathfinding: Examples in Unity7 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. 8. Pathfinding: Examples in Unity8 Tags: mostly for finding game objects(docs.unity3d.com:Tags) Layers: mostly for rendering purposes(docs.unity3d.com:Layers)
  9. 9. Pathfinding: Examples in Unity9 Here we specify two layers Ground Obstacles And set the plane and crates tothe correct one
  10. 10. Pathfinding: Examples in Unity10 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. 11. Pathfinding: Examples in Unity11 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 bycollisions (also step offset, slope limit)
  12. 12. Pathfinding: Examples in Unity12 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. 13. Pathfinding: Ex. in Unity13 Specify the parameters of theAstarPath 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. 14. Pathfinding: Ex. in Unity14 Capsule collider with diameter 2 8-connected
  15. 15. Pathfinding: Ex. in Unity15 Capsule collider with diameter 2 8-connected“Cut corners”option affectsthese edges
  16. 16. Pathfinding: Ex. in Unity16 Capsule collider with diameter 6 4-connected
  17. 17. Pathfinding: Examples in Unity17 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. 18. Pathfinding: Examples in Unity18 Using the Seeker script to get paths for Lerpzpublic class AstarAI1 : MonoBehaviour {public Vector3 targetPosition;public void Start () {//Get a reference to the Seeker componentSeeker seeker = GetComponent<Seeker>();//Start a new path to the targetPosition,//return the result to the OnPathComplete functionseeker.StartPath (transform.position,targetPosition,OnPathComplete);}public void OnPathComplete (Path p) {Debug.Log ("Yey, we got a path back!");}}
  19. 19. Pathfinding: Examples in Unity19 Astar A1 script calls the Seekers StartPath function The Seeker creates a new Path instance and sends it tothe AstarPath script (in the A* Pathfinder game-object) AstarPath script puts the path in a queue, whenavailable, it processes the path by searching the grid inthe A* heuristic search manner we described earlier AstarPAth script calls the function OnPathComplete withthe path it found as a parameter p p.VectorPath holds a list of Vector3 objects that showhow the destination can be reached
  20. 20. Pathfinding: Examples in Unity20 Seeker option to display path via gizmos
  21. 21. Pathfinding: Examples in Unity21 Post-processing path via modifiers (here: Funnell mod.)
  22. 22. Pathfinding: Examples in Unity22 Using Astar AI1 script, Lerpz is able to find out howto 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. 23. Pathfinding: Examples in Unity23public class AstarAI2 : MonoBehaviour {...//The calculated pathpublic Path path;//The character’s speedpublic float speed = 100;//The distance to a waypoint for moving to the nextpublic float nextWaypointDistance = 3;//The waypoint we are currently moving towardsprivate int currentWaypoint = 0;public void Start () {... }public void OnPathComplete (Path p) {... }public void FixedUpdate () {... }}
  24. 24. Pathfinding: Examples in Unity24public class AstarAI2 : MonoBehaviour {public void FixedUpdate () {//Check if we reached the destinationif (currentWaypoint >= path.vectorPath.Count) {Debug.Log ("End Of Path Reached");return;}//Direction to the next waypointVector3 dir = (path.vectorPath[currentWaypoint]-transform.position).normalized;dir *= speed * Time.fixedDeltaTime;controller.SimpleMove (dir);//Check if we need to switch to the next waypointif (Vector3.Distance(transform.position,path.vectorPath[currentWaypoint]) < nextWaypointDistance) {currentWaypoint++;return;}}
  25. 25. Pathfinding: Examples in Unity25 Lerpz moves but without animating its parts Basic animation of pre-defined clips Animation component (docs.unity3d.com:Animation) Play(“walk”), Stop()
  26. 26. Pathfinding: Examples in Unity26 Lerpz.fbx Embedded animations that havebeen created outside of Unity forthe 3D model Available for Playing Looping Blending
  27. 27. Pathfinding: Examples in Unity27public class AstarAI3 : MonoBehaviour {...//Cashed reference to Animation componentpublic 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. 28. Pathfinding: Examples in Unity28 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. 29. Pathfinding: Examples in Unity29 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. 30. Pathfinding: Examples in Unity30 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 collisionwith a game-object in the scene Use it to place crates Pressing “r” removes game-object
  31. 31. Pathfinding: Examples in Unity31public class TargetMover : MonoBehaviour {...//Handle continuous move in Update() functionvoid Update () {if (!onlyOnDoubleClick && cam != null) {UpdateTargetPosition ();}}public void UpdateTargetPosition () {//Define a ray from eye to mouse positionRay ray = cam.ScreenPointToRay (Input.mousePosition);//Do raycast and if it hits the given mask layerRaycastHit hit;if (Physics.Raycast(ray, out hit, Mathf.Infinity, mask)){//transport the target at the hit positiontarget.position = hit.point;}}
  32. 32. Pathfinding: Examples in Unity32public 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. 33. Pathfinding: Examples in Unity33 Scripts Astar AI1 Astar AI2 Astar AI3 Astar AI4 TargetMover ObjectPlacer Either as originally from Aron’s Pathfinding Project orwith slight modifications Use the ones in the project in Pathfinding.zip
  34. 34. Pathfinding: Examples in Unity34 Many crates
  35. 35. Pathfinding: Examples in Unity35 Many crates – How does Lerpz know to avoid them?
  36. 36. Pathfinding: Examples in Unity36public void PlaceObject () {Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);RaycastHit hit;//If we hit an objectif ( Physics.Raycast (ray, out hit, Mathf.Infinity)) {Vector3 p = hit.point;//Instantiate a new game-objectGameObject obj = (GameObject)GameObject.Instantiate(go,p,Quaternion.identity);//Update the pathfinding graphBounds b = obj.collider.bounds;GraphUpdateObject guo = new GraphUpdateObject(b);AstarPath.active.UpdateGraphs (guo);}}
  37. 37. Pathfinding: Examples in Unity37 Local updates are faster if we have a huge map But can be problematic when objects end up fartheraway or may fall on the ground later than the update
  38. 38. Pathfinding: Examples in Unity38 Many Lerpzs!
  39. 39. Pathfinding: Examples in Unity39 Many Lerpzs! FPS decreases even for just 10 NPCs
  40. 40. Pathfinding: Examples in Unity40 Grids can only go so far
  41. 41. Pathfinding: Examples in Unity41 Open scene “Pathfiding on platforms”
  42. 42. Pathfinding: Unity42 Height testing Similar to obstacles Use “Ground” layer to identifyareas that are walkable Raycasting
  43. 43. Pathfinding: Examples in Unity43 We can still tweak our grid to do the job
  44. 44. Pathfinding: Unity44 Or we can use a graph (Pointgraph, dist=4)
  45. 45. Pathfinding: Unity45 Or we can use a graph (Pointgraph, dist=4)
  46. 46. Pathfinding Part 3: Beyond the basics46 Many neat tricks for efficient/nice pathfinding Alternative game-world representations Beyond A* Better heuristics

×