18_CharacterDemo.lua 17 KB

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