CharacterDemo.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. #include "AnimatedModel.h"
  2. #include "AnimationController.h"
  3. #include "Camera.h"
  4. #include "CollisionShape.h"
  5. #include "Context.h"
  6. #include "Controls.h"
  7. #include "CoreEvents.h"
  8. #include "DebugRenderer.h"
  9. #include "Engine.h"
  10. #include "Font.h"
  11. #include "Input.h"
  12. #include "Light.h"
  13. #include "Material.h"
  14. #include "MemoryBuffer.h"
  15. #include "Model.h"
  16. #include "Octree.h"
  17. #include "PhysicsEvents.h"
  18. #include "PhysicsWorld.h"
  19. #include "ProcessUtils.h"
  20. #include "Renderer.h"
  21. #include "RigidBody.h"
  22. #include "ResourceCache.h"
  23. #include "Scene.h"
  24. #include "StaticModel.h"
  25. #include "Text.h"
  26. #include "UI.h"
  27. #include "Zone.h"
  28. #include "Main.h"
  29. #include "DebugNew.h"
  30. using namespace Urho3D;
  31. const int CTRL_UP = 1;
  32. const int CTRL_DOWN = 2;
  33. const int CTRL_LEFT = 4;
  34. const int CTRL_RIGHT = 8;
  35. const int CTRL_FIRE = 16;
  36. const int CTRL_JUMP = 32;
  37. const int CTRL_ALL = 63;
  38. const float MOVE_FORCE = 0.8f;
  39. const float INAIR_MOVE_FORCE = 0.02f;
  40. const float BRAKE_FORCE = 0.2f;
  41. const float JUMP_FORCE = 7.0f;
  42. const float YAW_SENSITIVITY = 0.1f;
  43. const float INAIR_THRESHOLD_TIME = 0.1f;
  44. const float CAMERA_MIN_DIST = 1.0f;
  45. const float CAMERA_MAX_DIST = 5.0f;
  46. const float CAMERA_SAFETY_DIST = 0.5f;
  47. class Character : public Component
  48. {
  49. OBJECT(Character)
  50. public:
  51. /// Construct.
  52. Character(Context* context);
  53. /// Handle node being assigned.
  54. virtual void OnNodeSet(Node* node);
  55. /// Handle physics collision event.
  56. void HandleNodeCollision(StringHash eventType, VariantMap& eventData);
  57. /// Handle physics world update event.
  58. void HandleFixedUpdate(StringHash eventType, VariantMap& eventData);
  59. /// Movement controls.
  60. Controls controls_;
  61. /// Grounded flag for movement.
  62. bool onGround_;
  63. /// Jump flag.
  64. bool okToJump_;
  65. /// In air timer. Due to possible physics inaccuracy, character can be off ground for max. 1/10 second and still be allowed to move.
  66. float inAirTimer_;
  67. };
  68. class CharacterDemo : public Object
  69. {
  70. OBJECT(CharacterDemo);
  71. public:
  72. /// Construct.
  73. CharacterDemo(Context* context);
  74. /// Initialize.
  75. void Start();
  76. private:
  77. /// Create static scene content.
  78. void CreateScene();
  79. /// Create controllable character.
  80. void CreateCharacter();
  81. /// Subscribe to necessary events.
  82. void SubscribeToEvents();
  83. /// Handle application update. Set controls to character & check global keys.
  84. void HandleUpdate(StringHash eventType, VariantMap& eventData);
  85. /// Handle application post-update. Update camera position after character has moved.
  86. void HandlePostUpdate(StringHash eventType, VariantMap& eventData);
  87. /// Scene.
  88. SharedPtr<Scene> scene_;
  89. /// Resource cache subsystem, stored here for convenience.
  90. SharedPtr<ResourceCache> cache_;
  91. /// Camera scene node.
  92. SharedPtr<Node> cameraNode_;
  93. /// The controllable character.
  94. WeakPtr<Character> character_;
  95. /// First person camera flag.
  96. bool firstPerson_;
  97. };
  98. int Run()
  99. {
  100. SharedPtr<Context> context(new Context());
  101. SharedPtr<Engine> engine(new Engine(context));
  102. engine->Initialize("Character", "Character.log", GetArguments());
  103. SharedPtr<CharacterDemo> characterDemo(new CharacterDemo(context));
  104. characterDemo->Start();
  105. while (!engine->IsExiting())
  106. engine->RunFrame();
  107. return 0;
  108. }
  109. DEFINE_MAIN(Run())
  110. OBJECTTYPESTATIC(CharacterDemo);
  111. OBJECTTYPESTATIC(Character);
  112. CharacterDemo::CharacterDemo(Context* context) :
  113. Object(context),
  114. cache_(GetSubsystem<ResourceCache>()),
  115. firstPerson_(false)
  116. {
  117. // Register factory for the Character component so it can be created via CreateComponent
  118. context_->RegisterFactory<Character>();
  119. }
  120. void CharacterDemo::Start()
  121. {
  122. CreateScene();
  123. CreateCharacter();
  124. SubscribeToEvents();
  125. }
  126. void CharacterDemo::CreateScene()
  127. {
  128. scene_ = new Scene(context_);
  129. // Create scene subsystem components
  130. scene_->CreateComponent<Octree>();
  131. scene_->CreateComponent<PhysicsWorld>();
  132. scene_->CreateComponent<DebugRenderer>();
  133. // Create camera and define viewport. Camera does not necessarily have to belong to the scene
  134. cameraNode_ = new Node(context_);
  135. Camera* camera = cameraNode_->CreateComponent<Camera>();
  136. GetSubsystem<Renderer>()->SetViewport(0, new Viewport(context_, scene_, camera));
  137. // Create static scene content, same as in TestScene.as
  138. Node* zoneNode = scene_->CreateChild("Zone");
  139. Zone* zone = zoneNode->CreateComponent<Zone>();
  140. zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));
  141. zone->SetFogColor(Color(0.5f, 0.5f, 0.7f));
  142. zone->SetFogStart(100.0f);
  143. zone->SetFogEnd(300.0f);
  144. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  145. {
  146. Node* lightNode = scene_->CreateChild("GlobalLight");
  147. lightNode->SetDirection(Vector3(0.3f, -0.5f, 0.425f));
  148. Light* light = lightNode->CreateComponent<Light>();
  149. light->SetLightType(LIGHT_DIRECTIONAL);
  150. light->SetCastShadows(true);
  151. light->SetShadowBias(BiasParameters(0.0001f, 0.5f));
  152. light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
  153. light->SetSpecularIntensity(0.5f);
  154. }
  155. {
  156. Node* objectNode = scene_->CreateChild("Floor");
  157. objectNode->SetPosition(Vector3(0.0f, -0.5f, 0.0f));
  158. objectNode->SetScale(Vector3(200.0f, 1.0f, 200.0f));
  159. StaticModel* object = objectNode->CreateComponent<StaticModel>();
  160. object->SetModel(cache_->GetResource<Model>("Models/Box.mdl"));
  161. object->SetMaterial(cache_->GetResource<Material>("Materials/Stone.xml"));
  162. object->SetOccluder(true);
  163. RigidBody* body = objectNode->CreateComponent<RigidBody>();
  164. CollisionShape* shape = objectNode->CreateComponent<CollisionShape>();
  165. shape->SetBox(Vector3::ONE);
  166. }
  167. for (unsigned i = 0; i < 50; ++i)
  168. {
  169. Node* objectNode = scene_->CreateChild("Box");
  170. objectNode->SetPosition(Vector3(Random() * 180.0f - 90.0f, 1.0f, Random() * 180.0f - 90.0f));
  171. objectNode->SetScale(2.0f);
  172. StaticModel* object = objectNode->CreateComponent<StaticModel>();
  173. object->SetModel(cache_->GetResource<Model>("Models/Box.mdl"));
  174. object->SetMaterial(cache_->GetResource<Material>("Materials/Stone.xml"));
  175. object->SetCastShadows(true);
  176. RigidBody* body = objectNode->CreateComponent<RigidBody>();
  177. CollisionShape* shape = objectNode->CreateComponent<CollisionShape>();
  178. shape->SetBox(Vector3::ONE);
  179. }
  180. for (unsigned i = 0; i < 10; ++i)
  181. {
  182. Node* objectNode = scene_->CreateChild("Box");
  183. objectNode->SetPosition(Vector3(Random() * 180.0f - 90.0f, 10.0f, Random() * 180.0f - 90.0f));
  184. objectNode->SetScale(20);
  185. StaticModel* object = objectNode->CreateComponent<StaticModel>();
  186. object->SetModel(cache_->GetResource<Model>("Models/Box.mdl"));
  187. object->SetMaterial(cache_->GetResource<Material>("Materials/Stone.xml"));
  188. object->SetCastShadows(true);
  189. object->SetOccluder(true);
  190. RigidBody* body = objectNode->CreateComponent<RigidBody>();
  191. CollisionShape* shape = objectNode->CreateComponent<CollisionShape>();
  192. shape->SetBox(Vector3::ONE);
  193. }
  194. for (unsigned i = 0; i < 50; ++i)
  195. {
  196. Node* objectNode = scene_->CreateChild("Mushroom");
  197. objectNode->SetPosition(Vector3(Random() * 180.0f - 90.0f, 0.0f, Random() * 180.0f - 90.0f));
  198. objectNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));
  199. objectNode->SetScale(5.0f);
  200. StaticModel* object = objectNode->CreateComponent<StaticModel>();
  201. object->SetModel(cache_->GetResource<Model>("Models/Mushroom.mdl"));
  202. object->SetMaterial(cache_->GetResource<Material>("Materials/Mushroom.xml"));
  203. object->SetCastShadows(true);
  204. RigidBody* body = objectNode->CreateComponent<RigidBody>();
  205. CollisionShape* shape = objectNode->CreateComponent<CollisionShape>();
  206. shape->SetTriangleMesh(object->GetModel(), 0);
  207. }
  208. }
  209. void CharacterDemo::CreateCharacter()
  210. {
  211. Node* objectNode = scene_->CreateChild("Jack");
  212. objectNode->SetPosition(Vector3(0.0f, 1.0f, 0.0f));
  213. AnimatedModel* object = objectNode->CreateComponent<AnimatedModel>();
  214. object->SetModel(cache_->GetResource<Model>("Models/Jack.mdl"));
  215. object->SetMaterial(cache_->GetResource<Material>("Materials/Jack.xml"));
  216. object->SetCastShadows(true);
  217. AnimationController* ctrl = objectNode->CreateComponent<AnimationController>();
  218. // Create rigidbody, and set non-zero mass so that the body becomes dynamic
  219. RigidBody* body = objectNode->CreateComponent<RigidBody>();
  220. body->SetMass(1.0f);
  221. // Set zero angular factor so that physics doesn't turn the character on its own.
  222. // Instead we will control the character yaw manually
  223. body->SetAngularFactor(Vector3::ZERO);
  224. // Set the rigid body to signal collision also when in rest, so that we get ground collisions properly
  225. body->SetCollisionEventMode(COLLISION_ALWAYS);
  226. // Set a capsule shape for character collision
  227. CollisionShape* shape = objectNode->CreateComponent<CollisionShape>();
  228. shape->SetCapsule(0.7f, 1.8f, Vector3(0.0f, 0.9f, 0.0f));
  229. // Create our logic component, which takes care of steering the character
  230. // Remember the character so that we can set its controls. Use a WeakPtr because the scene hierarchy already owns it
  231. // and keeps it alive as long as it's not removed from the hierarchy
  232. character_ = objectNode->CreateComponent<Character>();
  233. }
  234. void CharacterDemo::SubscribeToEvents()
  235. {
  236. SubscribeToEvent(E_UPDATE, HANDLER(CharacterDemo, HandleUpdate));
  237. SubscribeToEvent(E_POSTUPDATE, HANDLER(CharacterDemo, HandlePostUpdate));
  238. }
  239. void CharacterDemo::HandleUpdate(StringHash eventType, VariantMap& eventData)
  240. {
  241. float timeStep = eventData[Update::P_TIMESTEP].GetFloat();
  242. Input* input = GetSubsystem<Input>();
  243. if (input->GetKeyDown(KEY_ESC))
  244. GetSubsystem<Engine>()->Exit();
  245. if (input->GetKeyPress('F'))
  246. firstPerson_ = !firstPerson_;
  247. if (character_)
  248. {
  249. // Get movement controls and assign them to the character
  250. character_->controls_.Set(CTRL_UP, input->GetKeyDown('W'));
  251. character_->controls_.Set(CTRL_DOWN, input->GetKeyDown('S'));
  252. character_->controls_.Set(CTRL_LEFT, input->GetKeyDown('A'));
  253. character_->controls_.Set(CTRL_RIGHT, input->GetKeyDown('D'));
  254. character_->controls_.Set(CTRL_JUMP, input->GetKeyDown(KEY_SPACE));
  255. // Add character yaw & pitch from the mouse motion
  256. character_->controls_.yaw_ += (float)input->GetMouseMoveX() * YAW_SENSITIVITY;
  257. character_->controls_.pitch_ += (float)input->GetMouseMoveY() * YAW_SENSITIVITY;
  258. // Limit pitch
  259. character_->controls_.pitch_ = Clamp(character_->controls_.pitch_, -80.0f, 80.0f);
  260. // Set rotation already here so that it's updated every rendering frame instead of every physics frame
  261. character_->GetNode()->SetRotation(Quaternion(character_->controls_.yaw_, Vector3::UP));
  262. }
  263. }
  264. void CharacterDemo::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  265. {
  266. if (!character_)
  267. return;
  268. Node* characterNode = character_->GetNode();
  269. // Get camera lookat dir from character yaw + pitch
  270. Quaternion rot = characterNode->GetRotation();
  271. Quaternion dir = rot * Quaternion(character_->controls_.pitch_, Vector3::RIGHT);
  272. if (firstPerson_)
  273. {
  274. // First person camera: position to the head bone + offset slightly forward & up
  275. Node* headNode = characterNode->GetChild("Bip01_Head", true);
  276. if (headNode)
  277. {
  278. cameraNode_->SetPosition(headNode->GetWorldPosition() + dir * Vector3(0.0f, 0.2f, 0.2f));
  279. cameraNode_->SetRotation(dir);
  280. }
  281. }
  282. else
  283. {
  284. // Third person camera: position behind the character
  285. Vector3 aimPoint = characterNode->GetPosition() + Vector3(0.0f, 1.75f, 0.0f);
  286. Vector3 minDist = aimPoint + dir * Vector3(0, 0, -CAMERA_MIN_DIST);
  287. Vector3 maxDist = aimPoint + dir * Vector3(0, 0, -CAMERA_MAX_DIST);
  288. // Collide camera ray with physics world to ensure we see the character properly
  289. Vector3 rayDir = (maxDist - minDist).Normalized();
  290. float rayDistance = CAMERA_MAX_DIST - CAMERA_MIN_DIST + CAMERA_SAFETY_DIST;
  291. PhysicsRaycastResult result;
  292. scene_->GetComponent<PhysicsWorld>()->RaycastSingle(result, Ray(minDist, rayDir), rayDistance);
  293. if (result.body_)
  294. rayDistance = Min(rayDistance, result.distance_ - CAMERA_SAFETY_DIST);
  295. cameraNode_->SetPosition(minDist + rayDir * rayDistance);
  296. cameraNode_->SetRotation(dir);
  297. }
  298. }
  299. Character::Character(Context* context) :
  300. Component(context),
  301. onGround_(false),
  302. okToJump_(true),
  303. inAirTimer_(0.0f)
  304. {
  305. }
  306. void Character::OnNodeSet(Node* node)
  307. {
  308. // Component has been inserted into its scene node. Subscribe to events now
  309. SubscribeToEvent(node, E_NODECOLLISION, HANDLER(Character, HandleNodeCollision));
  310. SubscribeToEvent(GetScene()->GetComponent<PhysicsWorld>(), E_PHYSICSPRESTEP, HANDLER(Character, HandleFixedUpdate));
  311. }
  312. void Character::HandleNodeCollision(StringHash eventType, VariantMap& eventData)
  313. {
  314. // Check collision contacts and see if character is standing on ground (look for a contact that has near vertical normal)
  315. using namespace NodeCollision;
  316. MemoryBuffer contacts(eventData[P_CONTACTS].GetBuffer());
  317. while (!contacts.IsEof())
  318. {
  319. Vector3 contactPosition = contacts.ReadVector3();
  320. Vector3 contactNormal = contacts.ReadVector3();
  321. float contactDistance = contacts.ReadFloat();
  322. float contactImpulse = contacts.ReadFloat();
  323. // If contact is below node center and mostly vertical, assume it's a ground contact
  324. if (contactPosition.y_ < (node_->GetPosition().y_ + 1.0f))
  325. {
  326. float level = Abs(contactNormal.y_);
  327. if (level > 0.75)
  328. onGround_ = true;
  329. }
  330. }
  331. }
  332. void Character::HandleFixedUpdate(StringHash eventType, VariantMap& eventData)
  333. {
  334. using namespace PhysicsPreStep;
  335. float timeStep = eventData[P_TIMESTEP].GetFloat();
  336. /// \todo Could cache the components for faster access instead of finding them each frame
  337. RigidBody* body = GetComponent<RigidBody>();
  338. AnimationController* animCtrl = GetComponent<AnimationController>();
  339. // Update the in air timer. Reset if grounded
  340. if (!onGround_)
  341. inAirTimer_ += timeStep;
  342. else
  343. inAirTimer_ = 0.0f;
  344. // When character has been in air less than 1/10 second, it's still interpreted as being on ground
  345. bool softGrounded = inAirTimer_ < INAIR_THRESHOLD_TIME;
  346. // Update movement & animation
  347. const Quaternion& rot = node_->GetRotation();
  348. Vector3 moveDir = Vector3::ZERO;
  349. const Vector3& velocity = body->GetLinearVelocity();
  350. // Velocity on the XZ plane
  351. Vector3 planeVelocity(velocity.x_, 0.0f, velocity.z_);
  352. if (controls_.IsDown(CTRL_UP))
  353. moveDir += Vector3::FORWARD;
  354. if (controls_.IsDown(CTRL_DOWN))
  355. moveDir += Vector3::BACK;
  356. if (controls_.IsDown(CTRL_LEFT))
  357. moveDir += Vector3::LEFT;
  358. if (controls_.IsDown(CTRL_RIGHT))
  359. moveDir += Vector3::RIGHT;
  360. // Normalize move vector so that diagonal strafing is not faster
  361. if (moveDir.LengthSquared() > 0.0f)
  362. moveDir.Normalize();
  363. // If in air, allow control, but slower than when on ground
  364. body->ApplyImpulse(rot * moveDir * (softGrounded ? MOVE_FORCE : INAIR_MOVE_FORCE));
  365. if (softGrounded)
  366. {
  367. // When on ground, apply a braking force to limit maximum ground velocity
  368. Vector3 brakeForce = -planeVelocity * BRAKE_FORCE;
  369. body->ApplyImpulse(brakeForce);
  370. // Jump. Must release jump control inbetween jumps
  371. if (controls_.IsDown(CTRL_JUMP))
  372. {
  373. if (okToJump_)
  374. {
  375. body->ApplyImpulse(Vector3::UP * JUMP_FORCE);
  376. okToJump_ = false;
  377. }
  378. }
  379. else
  380. okToJump_ = true;
  381. }
  382. // Play walk animation if moving on ground, otherwise fade it out
  383. if (softGrounded && !moveDir.Equals(Vector3::ZERO))
  384. animCtrl->PlayExclusive("Models/Jack_Walk.ani", 0, true, 0.2f);
  385. else
  386. animCtrl->Stop("Models/Jack_Walk.ani", 0.2f);
  387. // Set walk animation speed proportional to velocity
  388. animCtrl->SetSpeed("Models/Jack_Walk.ani", planeVelocity.Length() * 0.3f);
  389. // Reset grounded flag for next frame
  390. onGround_ = false;
  391. }