18_CharacterDemo.lua 17 KB

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