39_CrowdNavigation.as 25 KB

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