18_CharacterDemo.as 18 KB

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