18_CharacterDemo.lua 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. -- Moving character example.
  2. -- This sample demonstrates:
  3. -- - Controlling a humanoid character through physics
  4. -- - Driving animations using the AnimationController component
  5. -- - Manual control of a bone scene node
  6. -- - Implementing 1st and 3rd person cameras, using raycasts to avoid the 3rd person camera clipping into scenery
  7. -- - Saving and loading the variables of a script object
  8. -- - Using touch inputs/gyroscope for iOS/Android (implemented through an external file)
  9. require "LuaScripts/Utilities/Sample"
  10. require "LuaScripts/Utilities/Touch"
  11. -- Variables used by external file are made global in order to be accessed
  12. CTRL_FORWARD = 1
  13. CTRL_BACK = 2
  14. CTRL_LEFT = 4
  15. CTRL_RIGHT = 8
  16. local CTRL_JUMP = 16
  17. local MOVE_FORCE = 0.8
  18. local INAIR_MOVE_FORCE = 0.02
  19. local BRAKE_FORCE = 0.2
  20. local JUMP_FORCE = 7.0
  21. local YAW_SENSITIVITY = 0.1
  22. local INAIR_THRESHOLD_TIME = 0.1
  23. firstPerson = false -- First person camera flag
  24. local characterNode = nil
  25. function Start()
  26. -- Execute the common startup for samples
  27. SampleStart()
  28. -- Create static scene content
  29. CreateScene()
  30. -- Create the controllable character
  31. CreateCharacter()
  32. -- Create the UI content
  33. CreateInstructions()
  34. -- Subscribe to necessary events
  35. SubscribeToEvents()
  36. end
  37. function CreateScene()
  38. scene_ = Scene()
  39. -- Create scene subsystem components
  40. scene_:CreateComponent("Octree")
  41. scene_:CreateComponent("PhysicsWorld")
  42. -- Create camera and define viewport. Camera does not necessarily have to belong to the scene
  43. cameraNode = Node()
  44. local camera = cameraNode:CreateComponent("Camera")
  45. camera.farClip = 300.0
  46. renderer:SetViewport(0, Viewport:new(scene_, camera))
  47. -- Create a Zone component for ambient lighting & fog control
  48. local zoneNode = scene_:CreateChild("Zone")
  49. local zone = zoneNode:CreateComponent("Zone")
  50. zone.boundingBox = BoundingBox(-1000.0, 1000.0)
  51. zone.ambientColor = Color(0.15, 0.15, 0.15)
  52. zone.fogColor = Color(0.5, 0.5, 0.7)
  53. zone.fogStart = 100.0
  54. zone.fogEnd = 300.0
  55. -- Create a directional light to the world. Enable cascaded shadows on it
  56. local lightNode = scene_:CreateChild("DirectionalLight")
  57. lightNode.direction = Vector3(0.6, -1.0, 0.8)
  58. local light = lightNode:CreateComponent("Light")
  59. light.lightType = LIGHT_DIRECTIONAL
  60. light.castShadows = true
  61. light.shadowBias = BiasParameters(0.00025, 0.5)
  62. -- Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  63. light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8)
  64. -- Create the floor object
  65. local floorNode = scene_:CreateChild("Floor")
  66. floorNode.position = Vector3(0.0, -0.5, 0.0)
  67. floorNode.scale = Vector3(200.0, 1.0, 200.0)
  68. local object = floorNode:CreateComponent("StaticModel")
  69. object.model = cache:GetResource("Model", "Models/Box.mdl")
  70. object.material = cache:GetResource("Material", "Materials/Stone.xml")
  71. local body = floorNode:CreateComponent("RigidBody")
  72. -- Use collision layer bit 2 to mark world scenery. This is what we will raycast against to prevent camera from going
  73. -- inside geometry
  74. body.collisionLayer = 2
  75. local shape = floorNode:CreateComponent("CollisionShape")
  76. shape:SetBox(Vector3(1.0, 1.0, 1.0))
  77. -- Create mushrooms of varying sizes
  78. local NUM_MUSHROOMS = 60
  79. for i = 1, NUM_MUSHROOMS do
  80. local objectNode = scene_:CreateChild("Mushroom")
  81. objectNode.position = Vector3(Random(180.0) - 90.0, 0.0, Random(180.0) - 90.0)
  82. objectNode.rotation = Quaternion(0.0, Random(360.0), 0.0)
  83. objectNode:SetScale(2.0 + Random(5.0))
  84. local object = objectNode:CreateComponent("StaticModel")
  85. object.model = cache:GetResource("Model", "Models/Mushroom.mdl")
  86. object.material = cache:GetResource("Material", "Materials/Mushroom.xml")
  87. object.castShadows = true
  88. local body = objectNode:CreateComponent("RigidBody")
  89. body.collisionLayer = 2
  90. local shape = objectNode:CreateComponent("CollisionShape")
  91. shape:SetTriangleMesh(object.model, 0)
  92. end
  93. -- Create movable boxes. Let them fall from the sky at first
  94. local NUM_BOXES = 100
  95. for i = 1, NUM_BOXES do
  96. local scale = Random(2.0) + 0.5
  97. local objectNode = scene_:CreateChild("Box")
  98. objectNode.position = Vector3(Random(180.0) - 90.0, Random(10.0) + 10.0, Random(180.0) - 90.0)
  99. objectNode.rotation = Quaternion(Random(360.0), Random(360.0), Random(360.0))
  100. objectNode:SetScale(scale)
  101. local object = objectNode:CreateComponent("StaticModel")
  102. object.model = cache:GetResource("Model", "Models/Box.mdl")
  103. object.material = cache:GetResource("Material", "Materials/Stone.xml")
  104. object.castShadows = true
  105. local body = objectNode:CreateComponent("RigidBody")
  106. body.collisionLayer = 2
  107. -- Bigger boxes will be heavier and harder to move
  108. body.mass = scale * 2.0
  109. local shape = objectNode:CreateComponent("CollisionShape")
  110. shape:SetBox(Vector3(1.0, 1.0, 1.0))
  111. end
  112. end
  113. function CreateCharacter()
  114. characterNode = scene_:CreateChild("Jack")
  115. characterNode.position = Vector3(0.0, 1.0, 0.0)
  116. -- Create the rendering component + animation controller
  117. local object = characterNode:CreateComponent("AnimatedModel")
  118. object.model = cache:GetResource("Model", "Models/Jack.mdl")
  119. object.material = cache:GetResource("Material", "Materials/Jack.xml")
  120. object.castShadows = true
  121. characterNode:CreateComponent("AnimationController")
  122. -- Set the head bone for manual control
  123. object.skeleton:GetBone("Bip01_Head").animated = false
  124. -- Create rigidbody, and set non-zero mass so that the body becomes dynamic
  125. local body = characterNode:CreateComponent("RigidBody")
  126. body.collisionLayer = 1
  127. body.mass = 1.0
  128. -- Set zero angular factor so that physics doesn't turn the character on its own.
  129. -- Instead we will control the character yaw manually
  130. body.angularFactor = Vector3(0.0, 0.0, 0.0)
  131. -- Set the rigidbody to signal collision also when in rest, so that we get ground collisions properly
  132. body.collisionEventMode = COLLISION_ALWAYS
  133. -- Set a capsule shape for collision
  134. local shape = characterNode:CreateComponent("CollisionShape")
  135. shape:SetCapsule(0.7, 1.8, Vector3(0.0, 0.9, 0.0))
  136. -- Create the character logic object, which takes care of steering the rigidbody
  137. characterNode:CreateScriptObject("Character")
  138. end
  139. function CreateInstructions()
  140. -- Construct new Text object, set string to display and font to use
  141. local instructionText = ui.root:CreateChild("Text")
  142. instructionText:SetText(
  143. "Use WASD keys and mouse to move\n"..
  144. "Space to jump, F to toggle 1st/3rd person\n"..
  145. "F5 to save scene, F7 to load")
  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 SubscribeToEvents()
  155. -- Subscribe to Update event for setting the character controls before physics simulation
  156. SubscribeToEvent("Update", "HandleUpdate")
  157. -- Subscribe to PostUpdate event for updating the camera position after physics simulation
  158. SubscribeToEvent("PostUpdate", "HandlePostUpdate")
  159. -- Unsubscribe the SceneUpdate event from base class as the camera node is being controlled in HandlePostUpdate() in this sample
  160. UnsubscribeFromEvent("SceneUpdate")
  161. end
  162. function HandleUpdate(eventType, eventData)
  163. if characterNode == nil then
  164. return
  165. end
  166. local character = characterNode:GetScriptObject()
  167. if character == nil then
  168. return
  169. end
  170. -- Clear previous controls
  171. character.controls:Set(CTRL_FORWARD + CTRL_BACK + CTRL_LEFT + CTRL_RIGHT + CTRL_JUMP, false)
  172. -- Update controls using touch utility
  173. if touchEnabled then UpdateTouches(character.controls) end
  174. -- Update controls using keys
  175. if ui.focusElement == nil then
  176. if not touchEnabled or not useGyroscope then
  177. if input:GetKeyDown(KEY_W) then character.controls:Set(CTRL_FORWARD, true) end
  178. if input:GetKeyDown(KEY_S) then character.controls:Set(CTRL_BACK, true) end
  179. if input:GetKeyDown(KEY_A) then character.controls:Set(CTRL_LEFT, true) end
  180. if input:GetKeyDown(KEY_D) then character.controls:Set(CTRL_RIGHT, true) end
  181. end
  182. if input:GetKeyDown(KEY_SPACE) then character.controls:Set(CTRL_JUMP, true) end
  183. -- Add character yaw & pitch from the mouse motion or touch input
  184. if touchEnabled then
  185. for i=0, input.numTouches - 1 do
  186. local state = input:GetTouch(i)
  187. if not state.touchedElement then -- Touch on empty space
  188. local camera = cameraNode:GetComponent("Camera")
  189. if not camera then return end
  190. character.controls.yaw = character.controls.yaw + TOUCH_SENSITIVITY * camera.fov / graphics.height * state.delta.x
  191. character.controls.pitch = character.controls.pitch + TOUCH_SENSITIVITY * camera.fov / graphics.height * state.delta.y
  192. end
  193. end
  194. else
  195. character.controls.yaw = character.controls.yaw + input.mouseMoveX * YAW_SENSITIVITY
  196. character.controls.pitch = character.controls.pitch + input.mouseMoveY * YAW_SENSITIVITY
  197. end
  198. -- Limit pitch
  199. character.controls.pitch = Clamp(character.controls.pitch, -80.0, 80.0)
  200. -- Switch between 1st and 3rd person
  201. if input:GetKeyPress(KEY_F) then
  202. firstPerson = not firstPerson
  203. end
  204. -- Turn on/off gyroscope on mobile platform
  205. if input:GetKeyPress(KEY_G) then
  206. useGyroscope = not useGyroscope
  207. end
  208. -- Check for loading / saving the scene
  209. if input:GetKeyPress(KEY_F5) then
  210. scene_:SaveXML(fileSystem:GetProgramDir().."Data/Scenes/CharacterDemo.xml")
  211. end
  212. if input:GetKeyPress(KEY_F7) then
  213. scene_:LoadXML(fileSystem:GetProgramDir().."Data/Scenes/CharacterDemo.xml")
  214. -- After loading we have to reacquire the character scene node, as it has been recreated
  215. -- Simply find by name as there's only one of them
  216. characterNode = scene_:GetChild("Jack", true)
  217. if characterNode == nil then
  218. return
  219. end
  220. end
  221. end
  222. -- Set rotation already here so that it's updated every rendering frame instead of every physics frame
  223. characterNode.rotation = Quaternion(character.controls.yaw, Vector3(0.0, 1.0, 0.0))
  224. end
  225. function HandlePostUpdate(eventType, eventData)
  226. if characterNode == nil then
  227. return
  228. end
  229. local character = characterNode:GetScriptObject()
  230. if character == nil then
  231. return
  232. end
  233. -- Get camera lookat dir from character yaw + pitch
  234. local rot = characterNode.rotation
  235. local dir = rot * Quaternion(character.controls.pitch, Vector3(1.0, 0.0, 0.0))
  236. -- Turn head to camera pitch, but limit to avoid unnatural animation
  237. local headNode = characterNode:GetChild("Bip01_Head", true)
  238. local limitPitch = Clamp(character.controls.pitch, -45.0, 45.0)
  239. local headDir = rot * Quaternion(limitPitch, Vector3(1.0, 0.0, 0.0))
  240. -- This could be expanded to look at an arbitrary target, now just look at a point in front
  241. local headWorldTarget = headNode.worldPosition + headDir * Vector3(0.0, 0.0, 1.0)
  242. headNode:LookAt(headWorldTarget, Vector3(0.0, 1.0, 0.0))
  243. -- Correct head orientation because LookAt assumes Z = forward, but the bone has been authored differently (Y = forward)
  244. headNode:Rotate(Quaternion(0.0, 90.0, 90.0))
  245. if firstPerson then
  246. -- First person camera: position to the head bone + offset slightly forward & up
  247. cameraNode.position = headNode.worldPosition + rot * Vector3(0.0, 0.15, 0.2)
  248. cameraNode.rotation = dir
  249. else
  250. -- Third person camera: position behind the character
  251. local aimPoint = characterNode.position + rot * Vector3(0.0, 1.7, 0.0) -- You can modify x Vector3 value to translate the fixed character position (indicative range[-2;2])
  252. -- Collide camera ray with static physics objects (layer bitmask 2) to ensure we see the character properly
  253. local rayDir = dir * Vector3(0.0, 0.0, -1.0) -- For indoor scenes you can use dir * Vector3(0.0, 0.0, -0.5) to prevent camera from crossing the walls
  254. local rayDistance = cameraDistance
  255. local result = scene_:GetComponent("PhysicsWorld"):RaycastSingle(Ray(aimPoint, rayDir), rayDistance, 2)
  256. if result.body ~= nil then
  257. rayDistance = Min(rayDistance, result.distance)
  258. end
  259. rayDistance = Clamp(rayDistance, CAMERA_MIN_DIST, cameraDistance)
  260. cameraNode.position = aimPoint + rayDir * rayDistance
  261. cameraNode.rotation = dir
  262. end
  263. end
  264. -- Character script object class
  265. Character = ScriptObject()
  266. function Character:Start()
  267. -- Character controls.
  268. self.controls = Controls()
  269. -- Grounded flag for movement.
  270. self.onGround = false
  271. -- Jump flag.
  272. self.okToJump = true
  273. -- In air timer. Due to possible physics inaccuracy, character can be off ground for max. 1/10 second and still be allowed to move.
  274. self.inAirTimer = 0.0
  275. self:SubscribeToEvent(self.node, "NodeCollision", "Character:HandleNodeCollision")
  276. end
  277. function Character:Load(deserializer)
  278. self.onGround = deserializer:ReadBool()
  279. self.okToJump = deserializer:ReadBool()
  280. self.inAirTimer = deserializer:ReadFloat()
  281. self.controls.yaw = deserializer:ReadFloat()
  282. self.controls.pitch = deserializer:ReadFloat()
  283. end
  284. function Character:Save(serializer)
  285. serializer:WriteBool(self.onGround)
  286. serializer:WriteBool(self.okToJump)
  287. serializer:WriteFloat(self.inAirTimer)
  288. serializer:WriteFloat(self.controls.yaw)
  289. serializer:WriteFloat(self.controls.pitch)
  290. end
  291. function Character:HandleNodeCollision(eventType, eventData)
  292. local contacts = eventData:GetBuffer("Contacts")
  293. while not contacts.eof do
  294. local contactPosition = contacts:ReadVector3()
  295. local contactNormal = contacts:ReadVector3()
  296. local contactDistance = contacts:ReadFloat()
  297. local contactImpulse = contacts:ReadFloat()
  298. -- If contact is below node center and mostly vertical, assume it's a ground contact
  299. if contactPosition.y < self.node.position.y + 1.0 then
  300. local level = Abs(contactNormal.y)
  301. if level > 0.75 then
  302. self.onGround = true
  303. end
  304. end
  305. end
  306. end
  307. function Character:FixedUpdate(timeStep)
  308. -- Could cache the components for faster access instead of finding them each frame
  309. local body = self.node:GetComponent("RigidBody")
  310. local animCtrl = self.node:GetComponent("AnimationController")
  311. -- Update the in air timer. Reset if grounded
  312. if not self.onGround then
  313. self.inAirTimer = self.inAirTimer + timeStep
  314. else
  315. self.inAirTimer = 0.0
  316. end
  317. -- When character has been in air less than 1/10 second, it's still interpreted as being on ground
  318. local softGrounded = self.inAirTimer < INAIR_THRESHOLD_TIME
  319. -- Update movement & animation
  320. local rot = self.node.rotation
  321. local moveDir = Vector3(0.0, 0.0, 0.0)
  322. local velocity = body.linearVelocity
  323. -- Velocity on the XZ plane
  324. local planeVelocity = Vector3(velocity.x, 0.0, velocity.z)
  325. if self.controls:IsDown(CTRL_FORWARD) then
  326. moveDir = moveDir + Vector3(0.0, 0.0, 1.0)
  327. end
  328. if self.controls:IsDown(CTRL_BACK) then
  329. moveDir = moveDir + Vector3(0.0, 0.0, -1.0)
  330. end
  331. if self.controls:IsDown(CTRL_LEFT) then
  332. moveDir = moveDir + Vector3(-1.0, 0.0, 0.0)
  333. end
  334. if self.controls:IsDown(CTRL_RIGHT) then
  335. moveDir = moveDir + Vector3(1.0, 0.0, 0.0)
  336. end
  337. -- Normalize move vector so that diagonal strafing is not faster
  338. if moveDir:LengthSquared() > 0.0 then
  339. moveDir:Normalize()
  340. end
  341. -- If in air, allow control, but slower than when on ground
  342. if softGrounded then
  343. body:ApplyImpulse(rot * moveDir * MOVE_FORCE)
  344. else
  345. body:ApplyImpulse(rot * moveDir * INAIR_MOVE_FORCE)
  346. end
  347. if softGrounded then
  348. -- When on ground, apply a braking force to limit maximum ground velocity
  349. local brakeForce = planeVelocity * -BRAKE_FORCE
  350. body:ApplyImpulse(brakeForce)
  351. -- Jump. Must release jump control inbetween jumps
  352. if self.controls:IsDown(CTRL_JUMP) then
  353. if self.okToJump then
  354. body:ApplyImpulse(Vector3(0.0, 1.0, 0.0) * JUMP_FORCE)
  355. self.okToJump = false
  356. end
  357. else
  358. self.okToJump = true
  359. end
  360. end
  361. -- Play walk animation if moving on ground, otherwise fade it out
  362. if softGrounded and not moveDir:Equals(Vector3(0.0, 0.0, 0.0)) then
  363. animCtrl:PlayExclusive("Models/Jack_Walk.ani", 0, true, 0.2)
  364. else
  365. animCtrl:Stop("Models/Jack_Walk.ani", 0.2)
  366. end
  367. -- Set walk animation speed proportional to velocity
  368. animCtrl:SetSpeed("Models/Jack_Walk.ani", planeVelocity:Length() * 0.3)
  369. -- Reset grounded flag for next frame
  370. self.onGround = false
  371. end
  372. -- Create XML patch instructions for screen joystick layout specific to this sample app
  373. function GetScreenJoystickPatchString()
  374. return
  375. "<patch>" ..
  376. " <add sel=\"/element\">" ..
  377. " <element type=\"Button\">" ..
  378. " <attribute name=\"Name\" value=\"Button3\" />" ..
  379. " <attribute name=\"Position\" value=\"-120 -120\" />" ..
  380. " <attribute name=\"Size\" value=\"96 96\" />" ..
  381. " <attribute name=\"Horiz Alignment\" value=\"Right\" />" ..
  382. " <attribute name=\"Vert Alignment\" value=\"Bottom\" />" ..
  383. " <attribute name=\"Texture\" value=\"Texture2D;Textures/TouchInput.png\" />" ..
  384. " <attribute name=\"Image Rect\" value=\"96 0 192 96\" />" ..
  385. " <attribute name=\"Hover Image Offset\" value=\"0 0\" />" ..
  386. " <attribute name=\"Pressed Image Offset\" value=\"0 0\" />" ..
  387. " <element type=\"Text\">" ..
  388. " <attribute name=\"Name\" value=\"Label\" />" ..
  389. " <attribute name=\"Horiz Alignment\" value=\"Center\" />" ..
  390. " <attribute name=\"Vert Alignment\" value=\"Center\" />" ..
  391. " <attribute name=\"Color\" value=\"0 0 0 1\" />" ..
  392. " <attribute name=\"Text\" value=\"Gyroscope\" />" ..
  393. " </element>" ..
  394. " <element type=\"Text\">" ..
  395. " <attribute name=\"Name\" value=\"KeyBinding\" />" ..
  396. " <attribute name=\"Text\" value=\"G\" />" ..
  397. " </element>" ..
  398. " </element>" ..
  399. " </add>" ..
  400. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" ..
  401. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">1st/3rd</replace>" ..
  402. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" ..
  403. " <element type=\"Text\">" ..
  404. " <attribute name=\"Name\" value=\"KeyBinding\" />" ..
  405. " <attribute name=\"Text\" value=\"F\" />" ..
  406. " </element>" ..
  407. " </add>" ..
  408. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" ..
  409. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Jump</replace>" ..
  410. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" ..
  411. " <element type=\"Text\">" ..
  412. " <attribute name=\"Name\" value=\"KeyBinding\" />" ..
  413. " <attribute name=\"Text\" value=\"SPACE\" />" ..
  414. " </element>" ..
  415. " </add>" ..
  416. "</patch>"
  417. end