39_CrowdNavigation.lua 27 KB

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