18_CharacterDemo.as 21 KB

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