18_CharacterDemo.lua 21 KB

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