39_CrowdNavigation.as 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. // CrowdNavigation example.
  2. // This sample demonstrates:
  3. // - Generating a dynamic navigation mesh into the scene
  4. // - Performing path queries to the navigation mesh
  5. // - Adding and removing obstacles/agents at runtime
  6. // - Raycasting drawable components
  7. // - Crowd movement management
  8. // - Accessing crowd agents with the crowd manager
  9. // - Using off-mesh connections to make boxes climbable
  10. // - Using agents to simulate moving obstacles
  11. #include "Scripts/Utilities/Sample.as"
  12. const String INSTRUCTION("instructionText");
  13. void Start()
  14. {
  15. // Execute the common startup for samples
  16. SampleStart();
  17. // Create the scene content
  18. CreateScene();
  19. // Create the UI content
  20. CreateUI();
  21. // Setup the viewport for displaying the scene
  22. SetupViewport();
  23. // Hook up to the frame update and render post-update events
  24. SubscribeToEvents();
  25. }
  26. void CreateScene()
  27. {
  28. scene_ = Scene();
  29. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  30. // Also create a DebugRenderer component so that we can draw debug geometry
  31. scene_.CreateComponent("Octree");
  32. scene_.CreateComponent("DebugRenderer");
  33. // Create scene node & StaticModel component for showing a static plane
  34. Node@ planeNode = scene_.CreateChild("Plane");
  35. planeNode.scale = Vector3(100.0f, 1.0f, 100.0f);
  36. StaticModel@ planeObject = planeNode.CreateComponent("StaticModel");
  37. planeObject.model = cache.GetResource("Model", "Models/Plane.mdl");
  38. planeObject.material = cache.GetResource("Material", "Materials/StoneTiled.xml");
  39. // Create a Zone component for ambient lighting & fog control
  40. Node@ zoneNode = scene_.CreateChild("Zone");
  41. Zone@ zone = zoneNode.CreateComponent("Zone");
  42. zone.boundingBox = BoundingBox(-1000.0f, 1000.0f);
  43. zone.ambientColor = Color(0.15f, 0.15f, 0.15f);
  44. zone.fogColor = Color(0.5f, 0.5f, 0.7f);
  45. zone.fogStart = 100.0f;
  46. zone.fogEnd = 300.0f;
  47. // Create a directional light to the world. Enable cascaded shadows on it
  48. Node@ lightNode = scene_.CreateChild("DirectionalLight");
  49. lightNode.direction = Vector3(0.6f, -1.0f, 0.8f);
  50. Light@ light = lightNode.CreateComponent("Light");
  51. light.lightType = LIGHT_DIRECTIONAL;
  52. light.castShadows = true;
  53. light.shadowBias = BiasParameters(0.00025f, 0.5f);
  54. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  55. light.shadowCascade = CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
  56. // Create randomly sized boxes. If boxes are big enough, make them occluders. Occluders will be software rasterized before
  57. // rendering to a low-resolution depth-only buffer to test the objects in the view frustum for visibility
  58. Node@ boxGroup = scene_.CreateChild("Boxes");
  59. for (uint i = 0; i < 20; ++i)
  60. {
  61. Node@ boxNode = boxGroup.CreateChild("Box");
  62. float size = 1.0f + Random(10.0f);
  63. boxNode.position = Vector3(Random(80.0f) - 40.0f, size * 0.5f, Random(80.0f) - 40.0f);
  64. boxNode.SetScale(size);
  65. StaticModel@ boxObject = boxNode.CreateComponent("StaticModel");
  66. boxObject.model = cache.GetResource("Model", "Models/Box.mdl");
  67. boxObject.material = cache.GetResource("Material", "Materials/Stone.xml");
  68. boxObject.castShadows = true;
  69. if (size >= 3.0f)
  70. boxObject.occluder = true;
  71. }
  72. // Create a DynamicNavigationMesh component to the scene root
  73. DynamicNavigationMesh@ navMesh = scene_.CreateComponent("DynamicNavigationMesh");
  74. // Enable drawing debug geometry for obstacles and off-mesh connections
  75. navMesh.drawObstacles = true;
  76. navMesh.drawOffMeshConnections = true;
  77. // Set the agent height large enough to exclude the layers under boxes
  78. navMesh.agentHeight = 10;
  79. // Set nav mesh cell height to minimum (allows agents to be grounded)
  80. navMesh.cellHeight = 0.05f;
  81. // Create a Navigable component to the scene root. This tags all of the geometry in the scene as being part of the
  82. // navigation mesh. By default this is recursive, but the recursion could be turned off from Navigable
  83. scene_.CreateComponent("Navigable");
  84. // Add padding to the navigation mesh in Y-direction so that we can add objects on top of the tallest boxes
  85. // in the scene and still update the mesh correctly
  86. navMesh.padding = Vector3(0.0f, 10.0f, 0.0f);
  87. // Now build the navigation geometry. This will take some time. Note that the navigation mesh will prefer to use
  88. // physics geometry from the scene nodes, as it often is simpler, but if it can not find any (like in this example)
  89. // it will use renderable geometry instead
  90. navMesh.Build();
  91. // Create an off-mesh connection to each box to make it climbable (tiny boxes are skipped). A connection is built from 2 nodes.
  92. // Note that OffMeshConnections must be added before building the navMesh, but as we are adding Obstacles next, tiles will be automatically rebuilt.
  93. // Creating connections post-build here allows us to use FindNearestPoint() to procedurally set accurate positions for the connection
  94. CreateBoxOffMeshConnections(navMesh, boxGroup);
  95. // Create some mushrooms as obstacles. Note that obstacles are non-walkable areas
  96. for (uint i = 0; i < 100; ++i)
  97. CreateMushroom(Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f));
  98. // Create a CrowdManager component to the scene root (mandatory for crowd agents)
  99. CrowdManager@ crowdManager = scene_.CreateComponent("CrowdManager");
  100. CrowdObstacleAvoidanceParams params = crowdManager.GetObstacleAvoidanceParams(0);
  101. // Set the params to "High (66)" setting
  102. params.velBias = 0.5f;
  103. params.adaptiveDivs = 7;
  104. params.adaptiveRings = 3;
  105. params.adaptiveDepth = 3;
  106. crowdManager.SetObstacleAvoidanceParams(0, params);
  107. // Create some movable barrels. We create them as crowd agents, as for moving entities it is less expensive and more convenient than using obstacles
  108. CreateMovingBarrels(navMesh);
  109. // Create Jack node as crowd agent
  110. SpawnJack(Vector3(-5.0f, 0, 20.0f), scene_.CreateChild("Jacks"));
  111. // Create the camera. Limit far clip distance to match the fog. Note: now we actually create the camera node outside
  112. // the scene, because we want it to be unaffected by scene load / save
  113. cameraNode = Node();
  114. Camera@ camera = cameraNode.CreateComponent("Camera");
  115. camera.farClip = 300.0f;
  116. // Set an initial position for the camera scene node above the plane and looking down
  117. cameraNode.position = Vector3(0.0f, 50.0f, 0.0f);
  118. pitch = 80.0f;
  119. cameraNode.rotation = Quaternion(pitch, yaw, 0.0f);
  120. }
  121. void CreateUI()
  122. {
  123. // Create a Cursor UI element because we want to be able to hide and show it at will. When hidden, the mouse cursor will
  124. // control the camera, and when visible, it will point the raycast target
  125. XMLFile@ style = cache.GetResource("XMLFile", "UI/DefaultStyle.xml");
  126. Cursor@ cursor = Cursor();
  127. cursor.SetStyleAuto(style);
  128. ui.cursor = cursor;
  129. // Set starting position of the cursor at the rendering window center
  130. cursor.SetPosition(graphics.width / 2, graphics.height / 2);
  131. // Construct new Text object, set string to display and font to use
  132. Text@ instructionText = ui.root.CreateChild("Text", INSTRUCTION);
  133. instructionText.text =
  134. "Use WASD keys to move, RMB to rotate view\n"
  135. "LMB to set destination, SHIFT+LMB to spawn a Jack\n"
  136. "MMB or O key to add obstacles or remove obstacles/agents\n"
  137. "F5 to save scene, F7 to load\n"
  138. "Space to toggle debug geometry\n"
  139. "F12 to toggle this instruction text";
  140. instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15);
  141. // The text has multiple rows. Center them in relation to each other
  142. instructionText.textAlignment = HA_CENTER;
  143. // Position the text relative to the screen center
  144. instructionText.horizontalAlignment = HA_CENTER;
  145. instructionText.verticalAlignment = VA_CENTER;
  146. instructionText.SetPosition(0, ui.root.height / 4);
  147. }
  148. void SetupViewport()
  149. {
  150. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  151. Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera"));
  152. renderer.viewports[0] = viewport;
  153. }
  154. void SubscribeToEvents()
  155. {
  156. // Subscribe HandleUpdate() function for processing update events
  157. SubscribeToEvent("Update", "HandleUpdate");
  158. // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request debug geometry
  159. SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate");
  160. // Subscribe HandleCrowdAgentFailure() function for resolving invalidation issues with agents, during which we
  161. // use a larger extents for finding a point on the navmesh to fix the agent's position
  162. SubscribeToEvent("CrowdAgentFailure", "HandleCrowdAgentFailure");
  163. // Subscribe HandleCrowdAgentReposition() function for controlling the animation
  164. SubscribeToEvent("CrowdAgentReposition", "HandleCrowdAgentReposition");
  165. // Subscribe HandleCrowdAgentFormation() function for positioning agent into a formation
  166. SubscribeToEvent("CrowdAgentFormation", "HandleCrowdAgentFormation");
  167. }
  168. void CreateMushroom(const Vector3& pos)
  169. {
  170. Node@ mushroomNode = scene_.CreateChild("Mushroom");
  171. mushroomNode.position = pos;
  172. mushroomNode.rotation = Quaternion(0.0f, Random(360.0f), 0.0f);
  173. mushroomNode.SetScale(2.0f + Random(0.5f));
  174. StaticModel@ mushroomObject = mushroomNode.CreateComponent("StaticModel");
  175. mushroomObject.model = cache.GetResource("Model", "Models/Mushroom.mdl");
  176. mushroomObject.material = cache.GetResource("Material", "Materials/Mushroom.xml");
  177. mushroomObject.castShadows = true;
  178. // Create the navigation Obstacle component and set its height & radius proportional to scale
  179. Obstacle@ obstacle = mushroomNode.CreateComponent("Obstacle");
  180. obstacle.radius = mushroomNode.scale.x;
  181. obstacle.height = mushroomNode.scale.y;
  182. }
  183. void SpawnJack(const Vector3& pos, Node@ jackGroup)
  184. {
  185. Node@ jackNode = jackGroup.CreateChild("Jack");
  186. jackNode.position = pos;
  187. AnimatedModel@ modelObject = jackNode.CreateComponent("AnimatedModel");
  188. modelObject.model = cache.GetResource("Model", "Models/Jack.mdl");
  189. modelObject.material = cache.GetResource("Material", "Materials/Jack.xml");
  190. modelObject.castShadows = true;
  191. jackNode.CreateComponent("AnimationController");
  192. // Create a CrowdAgent component and set its height and realistic max speed/acceleration. Use default radius
  193. CrowdAgent@ agent = jackNode.CreateComponent("CrowdAgent");
  194. agent.height = 2.0f;
  195. agent.maxSpeed = 3.0f;
  196. agent.maxAccel = 3.0f;
  197. }
  198. void CreateBoxOffMeshConnections(DynamicNavigationMesh@ navMesh, Node@ boxGroup)
  199. {
  200. Array<Node@>@ boxes = boxGroup.GetChildren();
  201. for (uint i=0; i < boxes.length; ++i)
  202. {
  203. Node@ box = boxes[i];
  204. Vector3 boxPos = box.position;
  205. float boxHalfSize = box.scale.x / 2;
  206. // Create 2 empty nodes for the start & end points of the connection. Note that order matters only when using one-way/unidirectional connection.
  207. Node@ connectionStart = box.CreateChild("ConnectionStart");
  208. connectionStart.worldPosition = navMesh.FindNearestPoint(boxPos + Vector3(boxHalfSize, -boxHalfSize, 0)); // Base of box
  209. Node@ connectionEnd = connectionStart.CreateChild("ConnectionEnd");
  210. connectionEnd.worldPosition = navMesh.FindNearestPoint(boxPos + Vector3(boxHalfSize, boxHalfSize, 0)); // Top of box
  211. // Create the OffMeshConnection component to one node and link the other node
  212. OffMeshConnection@ connection = connectionStart.CreateComponent("OffMeshConnection");
  213. connection.endPoint = connectionEnd;
  214. }
  215. }
  216. void CreateMovingBarrels(DynamicNavigationMesh@ navMesh)
  217. {
  218. Node@ barrel = scene_.CreateChild("Barrel");
  219. StaticModel@ model = barrel.CreateComponent("StaticModel");
  220. model.model = cache.GetResource("Model", "Models/Cylinder.mdl");
  221. Material@ material = cache.GetResource("Material", "Materials/StoneTiled.xml");
  222. model.material = material;
  223. material.textures[TU_DIFFUSE] = cache.GetResource("Texture2D", "Textures/TerrainDetail2.dds");
  224. model.castShadows = true;
  225. for (uint i = 0; i < 20; ++i)
  226. {
  227. Node@ clone = barrel.Clone();
  228. float size = 0.5 + Random(1);
  229. clone.scale = Vector3(size / 1.5, size * 2.0, size / 1.5);
  230. clone.position = navMesh.FindNearestPoint(Vector3(Random(80.0) - 40.0, size * 0.5 , Random(80.0) - 40.0));
  231. CrowdAgent@ agent = clone.CreateComponent("CrowdAgent");
  232. agent.radius = clone.scale.x * 0.5f;
  233. agent.height = size;
  234. agent.navigationQuality = NAVIGATIONQUALITY_LOW;
  235. }
  236. barrel.Remove();
  237. }
  238. void SetPathPoint(bool spawning)
  239. {
  240. Vector3 hitPos;
  241. Drawable@ hitDrawable;
  242. if (Raycast(250.0f, hitPos, hitDrawable))
  243. {
  244. DynamicNavigationMesh@ navMesh = scene_.GetComponent("DynamicNavigationMesh");
  245. Vector3 pathPos = navMesh.FindNearestPoint(hitPos, Vector3(1.0f, 1.0f, 1.0f));
  246. Node@ jackGroup = scene_.GetChild("Jacks");
  247. if (spawning)
  248. // Spawn a jack at the target position
  249. SpawnJack(pathPos, jackGroup);
  250. else
  251. // Set crowd agents target position
  252. cast<CrowdManager>(scene_.GetComponent("CrowdManager")).SetCrowdTarget(pathPos, jackGroup);
  253. }
  254. }
  255. void AddOrRemoveObject()
  256. {
  257. // Raycast and check if we hit a mushroom node. If yes, remove it, if no, create a new one
  258. Vector3 hitPos;
  259. Drawable@ hitDrawable;
  260. if (Raycast(250.0f, hitPos, hitDrawable))
  261. {
  262. Node@ hitNode = hitDrawable.node;
  263. // Note that navmesh rebuild happens when the Obstacle component is removed
  264. if (hitNode.name == "Mushroom")
  265. hitNode.Remove();
  266. else if (hitNode.name == "Jack")
  267. hitNode.Remove();
  268. else
  269. CreateMushroom(hitPos);
  270. }
  271. }
  272. bool Raycast(float maxDistance, Vector3& hitPos, Drawable@& hitDrawable)
  273. {
  274. hitDrawable = null;
  275. IntVector2 pos = ui.cursorPosition;
  276. // Check the cursor is visible and there is no UI element in front of the cursor
  277. if (!ui.cursor.visible || ui.GetElementAt(pos, true) !is null)
  278. return false;
  279. Camera@ camera = cameraNode.GetComponent("Camera");
  280. Ray cameraRay = camera.GetScreenRay(float(pos.x) / graphics.width, float(pos.y) / graphics.height);
  281. // Pick only geometry objects, not eg. zones or lights, only get the first (closest) hit
  282. // Note the convenience accessor to scene's Octree component
  283. RayQueryResult result = scene_.octree.RaycastSingle(cameraRay, RAY_TRIANGLE, maxDistance, DRAWABLE_GEOMETRY);
  284. if (result.drawable !is null)
  285. {
  286. hitPos = result.position;
  287. hitDrawable = result.drawable;
  288. return true;
  289. }
  290. return false;
  291. }
  292. void MoveCamera(float timeStep)
  293. {
  294. // Right mouse button controls mouse cursor visibility: hide when pressed
  295. ui.cursor.visible = !input.mouseButtonDown[MOUSEB_RIGHT];
  296. // Do not move if the UI has a focused element (the console)
  297. if (ui.focusElement !is null)
  298. return;
  299. // Movement speed as world units per second
  300. const float MOVE_SPEED = 20.0f;
  301. // Mouse sensitivity as degrees per pixel
  302. const float MOUSE_SENSITIVITY = 0.1f;
  303. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  304. // Only move the camera when the cursor is hidden
  305. if (!ui.cursor.visible)
  306. {
  307. IntVector2 mouseMove = input.mouseMove;
  308. yaw += MOUSE_SENSITIVITY * mouseMove.x;
  309. pitch += MOUSE_SENSITIVITY * mouseMove.y;
  310. pitch = Clamp(pitch, -90.0f, 90.0f);
  311. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  312. cameraNode.rotation = Quaternion(pitch, yaw, 0.0f);
  313. }
  314. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  315. if (input.keyDown['W'])
  316. cameraNode.Translate(Vector3(0.0f, 0.0f, 1.0f) * MOVE_SPEED * timeStep);
  317. if (input.keyDown['S'])
  318. cameraNode.Translate(Vector3(0.0f, 0.0f, -1.0f) * MOVE_SPEED * timeStep);
  319. if (input.keyDown['A'])
  320. cameraNode.Translate(Vector3(-1.0f, 0.0f, 0.0f) * MOVE_SPEED * timeStep);
  321. if (input.keyDown['D'])
  322. cameraNode.Translate(Vector3(1.0f, 0.0f, 0.0f) * MOVE_SPEED * timeStep);
  323. // Set destination or spawn a jack with left mouse button
  324. if (input.mouseButtonPress[MOUSEB_LEFT])
  325. SetPathPoint(input.qualifierDown[QUAL_SHIFT]);
  326. // Add new obstacle or remove existing obstacle/agent with middle mouse button
  327. else if (input.mouseButtonPress[MOUSEB_MIDDLE] || input.keyPress['O'])
  328. AddOrRemoveObject();
  329. // Check for loading/saving the scene from/to the file Data/Scenes/CrowdNavigation.xml relative to the executable directory
  330. if (input.keyPress[KEY_F5])
  331. {
  332. File saveFile(fileSystem.programDir + "Data/Scenes/CrowdNavigation.xml", FILE_WRITE);
  333. scene_.SaveXML(saveFile);
  334. }
  335. else if (input.keyPress[KEY_F7])
  336. {
  337. File loadFile(fileSystem.programDir + "Data/Scenes/CrowdNavigation.xml", FILE_READ);
  338. scene_.LoadXML(loadFile);
  339. }
  340. // Toggle debug geometry with space
  341. else if (input.keyPress[KEY_SPACE])
  342. drawDebug = !drawDebug;
  343. // Toggle instruction text with F12
  344. else if (input.keyPress[KEY_F12])
  345. {
  346. UIElement@ instruction = ui.root.GetChild(INSTRUCTION);
  347. instruction.visible = !instruction.visible;
  348. }
  349. }
  350. void HandleUpdate(StringHash eventType, VariantMap& eventData)
  351. {
  352. // Take the frame time step, which is stored as a float
  353. float timeStep = eventData["TimeStep"].GetFloat();
  354. // Move the camera, scale movement with time step
  355. MoveCamera(timeStep);
  356. }
  357. void HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  358. {
  359. if (drawDebug)
  360. {
  361. // Visualize navigation mesh, obstacles and off-mesh connections
  362. cast<DynamicNavigationMesh>(scene_.GetComponent("DynamicNavigationMesh")).DrawDebugGeometry(true);
  363. // Visualize agents' path and position to reach
  364. cast<CrowdManager>(scene_.GetComponent("CrowdManager")).DrawDebugGeometry(true);
  365. }
  366. }
  367. void HandleCrowdAgentFailure(StringHash eventType, VariantMap& eventData)
  368. {
  369. Node@ node = eventData["Node"].GetPtr();
  370. int state = eventData["CrowdAgentState"].GetInt();
  371. // If the agent's state is invalid, likely from spawning on the side of a box, find a point in a larger area
  372. if (state == CA_STATE_INVALID)
  373. {
  374. // Get a point on the navmesh using more generous extents
  375. Vector3 newPos = cast<DynamicNavigationMesh>(scene_.GetComponent("DynamicNavigationMesh")).FindNearestPoint(node.position, Vector3(5.0f,5.0f,5.0f));
  376. // Set the new node position, CrowdAgent component will automatically reset the state of the agent
  377. node.position = newPos;
  378. }
  379. }
  380. void HandleCrowdAgentFormation(StringHash eventType, VariantMap& eventData)
  381. {
  382. uint index = eventData["Index"].GetUInt();
  383. uint size = eventData["Size"].GetUInt();
  384. Vector3 position = eventData["Position"].GetVector3();
  385. // The first agent will always move to the exact position, all other agents will select a random point nearby
  386. if (index > 0)
  387. {
  388. CrowdManager@ crowdManager =GetEventSender();
  389. CrowdAgent@ agent = eventData["CrowdAgent"].GetPtr();
  390. eventData["Position"] = crowdManager.GetRandomPointInCircle(position, agent.radius, agent.queryFilterType);
  391. }
  392. }
  393. void HandleCrowdAgentReposition(StringHash eventType, VariantMap& eventData)
  394. {
  395. const String WALKING_ANI = "Models/Jack_Walk.ani";
  396. const Vector3 FORWARD(0.0f, 0.0f, 1.0f);
  397. Node@ node = eventData["Node"].GetPtr();
  398. CrowdAgent@ agent = eventData["CrowdAgent"].GetPtr();
  399. Vector3 velocity = eventData["Velocity"].GetVector3();
  400. float timeStep = eventData["TimeStep"].GetFloat();
  401. // Only Jack agent has animation controller
  402. AnimationController@ animCtrl = node.GetComponent("AnimationController");
  403. if (animCtrl !is null)
  404. {
  405. float speed = velocity.length;
  406. if (animCtrl.IsPlaying(WALKING_ANI))
  407. {
  408. float speedRatio = speed / agent.maxSpeed;
  409. // Face the direction of its velocity but moderate the turning speed based on the speed ratio and timeStep
  410. node.rotation = node.rotation.Slerp(Quaternion(FORWARD, velocity), 10.f * timeStep * speedRatio);
  411. // Throttle the animation speed based on agent speed ratio (ratio = 1 is full throttle)
  412. animCtrl.SetSpeed(WALKING_ANI, speedRatio);
  413. }
  414. else
  415. animCtrl.Play(WALKING_ANI, 0, true, 0.1f);
  416. // If speed is too low then stopping the animation
  417. if (speed < agent.radius)
  418. animCtrl.Stop(WALKING_ANI, 0.8f);
  419. }
  420. }
  421. // Create XML patch instructions for screen joystick layout specific to this sample app
  422. String patchInstructions =
  423. "<patch>" +
  424. " <add sel=\"/element\">" +
  425. " <element type=\"Button\">" +
  426. " <attribute name=\"Name\" value=\"Button3\" />" +
  427. " <attribute name=\"Position\" value=\"-120 -120\" />" +
  428. " <attribute name=\"Size\" value=\"96 96\" />" +
  429. " <attribute name=\"Horiz Alignment\" value=\"Right\" />" +
  430. " <attribute name=\"Vert Alignment\" value=\"Bottom\" />" +
  431. " <attribute name=\"Texture\" value=\"Texture2D;Textures/TouchInput.png\" />" +
  432. " <attribute name=\"Image Rect\" value=\"96 0 192 96\" />" +
  433. " <attribute name=\"Hover Image Offset\" value=\"0 0\" />" +
  434. " <attribute name=\"Pressed Image Offset\" value=\"0 0\" />" +
  435. " <element type=\"Text\">" +
  436. " <attribute name=\"Name\" value=\"Label\" />" +
  437. " <attribute name=\"Horiz Alignment\" value=\"Center\" />" +
  438. " <attribute name=\"Vert Alignment\" value=\"Center\" />" +
  439. " <attribute name=\"Color\" value=\"0 0 0 1\" />" +
  440. " <attribute name=\"Text\" value=\"Spawn\" />" +
  441. " </element>" +
  442. " <element type=\"Text\">" +
  443. " <attribute name=\"Name\" value=\"KeyBinding\" />" +
  444. " <attribute name=\"Text\" value=\"LSHIFT\" />" +
  445. " </element>" +
  446. " <element type=\"Text\">" +
  447. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" +
  448. " <attribute name=\"Text\" value=\"LEFT\" />" +
  449. " </element>" +
  450. " </element>" +
  451. " <element type=\"Button\">" +
  452. " <attribute name=\"Name\" value=\"Button4\" />" +
  453. " <attribute name=\"Position\" value=\"-120 -12\" />" +
  454. " <attribute name=\"Size\" value=\"96 96\" />" +
  455. " <attribute name=\"Horiz Alignment\" value=\"Right\" />" +
  456. " <attribute name=\"Vert Alignment\" value=\"Bottom\" />" +
  457. " <attribute name=\"Texture\" value=\"Texture2D;Textures/TouchInput.png\" />" +
  458. " <attribute name=\"Image Rect\" value=\"96 0 192 96\" />" +
  459. " <attribute name=\"Hover Image Offset\" value=\"0 0\" />" +
  460. " <attribute name=\"Pressed Image Offset\" value=\"0 0\" />" +
  461. " <element type=\"Text\">" +
  462. " <attribute name=\"Name\" value=\"Label\" />" +
  463. " <attribute name=\"Horiz Alignment\" value=\"Center\" />" +
  464. " <attribute name=\"Vert Alignment\" value=\"Center\" />" +
  465. " <attribute name=\"Color\" value=\"0 0 0 1\" />" +
  466. " <attribute name=\"Text\" value=\"Obstacles\" />" +
  467. " </element>" +
  468. " <element type=\"Text\">" +
  469. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" +
  470. " <attribute name=\"Text\" value=\"MIDDLE\" />" +
  471. " </element>" +
  472. " </element>" +
  473. " </add>" +
  474. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" +
  475. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Set</replace>" +
  476. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" +
  477. " <element type=\"Text\">" +
  478. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" +
  479. " <attribute name=\"Text\" value=\"LEFT\" />" +
  480. " </element>" +
  481. " </add>" +
  482. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" +
  483. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Debug</replace>" +
  484. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" +
  485. " <element type=\"Text\">" +
  486. " <attribute name=\"Name\" value=\"KeyBinding\" />" +
  487. " <attribute name=\"Text\" value=\"SPACE\" />" +
  488. " </element>" +
  489. " </add>" +
  490. "</patch>";