Character.cpp 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "AnimationController.h"
  23. #include "Character.h"
  24. #include "Context.h"
  25. #include "MemoryBuffer.h"
  26. #include "PhysicsEvents.h"
  27. #include "PhysicsWorld.h"
  28. #include "RigidBody.h"
  29. #include "Scene.h"
  30. #include "SceneEvents.h"
  31. Character::Character(Context* context) :
  32. Component(context),
  33. onGround_(false),
  34. okToJump_(true),
  35. inAirTimer_(0.0f)
  36. {
  37. }
  38. void Character::RegisterObject(Context* context)
  39. {
  40. context->RegisterFactory<Character>();
  41. // These macros register the class attributes to the Context for automatic load / save handling.
  42. // We specify the Default attribute mode which means it will be used both for saving into file, and network replication
  43. ATTRIBUTE(Character, VAR_FLOAT, "Controls Yaw", controls_.yaw_, 0.0f, AM_DEFAULT);
  44. ATTRIBUTE(Character, VAR_FLOAT, "Controls Pitch", controls_.pitch_, 0.0f, AM_DEFAULT);
  45. ATTRIBUTE(Character, VAR_BOOL, "On Ground", onGround_, false, AM_DEFAULT);
  46. ATTRIBUTE(Character, VAR_BOOL, "OK To Jump", okToJump_, true, AM_DEFAULT);
  47. ATTRIBUTE(Character, VAR_FLOAT, "In Air Timer", inAirTimer_, 0.0f, AM_DEFAULT);
  48. }
  49. void Character::OnNodeSet(Node* node)
  50. {
  51. if (node)
  52. {
  53. // Component has been inserted into its scene node. Subscribe to events now
  54. SubscribeToEvent(node, E_NODECOLLISION, HANDLER(Character, HandleNodeCollision));
  55. SubscribeToEvent(GetScene()->GetComponent<PhysicsWorld>(), E_PHYSICSPRESTEP, HANDLER(Character, HandleFixedUpdate));
  56. }
  57. }
  58. void Character::HandleNodeCollision(StringHash eventType, VariantMap& eventData)
  59. {
  60. // Check collision contacts and see if character is standing on ground (look for a contact that has near vertical normal)
  61. using namespace NodeCollision;
  62. MemoryBuffer contacts(eventData[P_CONTACTS].GetBuffer());
  63. while (!contacts.IsEof())
  64. {
  65. Vector3 contactPosition = contacts.ReadVector3();
  66. Vector3 contactNormal = contacts.ReadVector3();
  67. float contactDistance = contacts.ReadFloat();
  68. float contactImpulse = contacts.ReadFloat();
  69. // If contact is below node center and mostly vertical, assume it's a ground contact
  70. if (contactPosition.y_ < (node_->GetPosition().y_ + 1.0f))
  71. {
  72. float level = Abs(contactNormal.y_);
  73. if (level > 0.75)
  74. onGround_ = true;
  75. }
  76. }
  77. }
  78. void Character::HandleFixedUpdate(StringHash eventType, VariantMap& eventData)
  79. {
  80. using namespace PhysicsPreStep;
  81. float timeStep = eventData[P_TIMESTEP].GetFloat();
  82. /// \todo Could cache the components for faster access instead of finding them each frame
  83. RigidBody* body = GetComponent<RigidBody>();
  84. AnimationController* animCtrl = GetComponent<AnimationController>();
  85. // Update the in air timer. Reset if grounded
  86. if (!onGround_)
  87. inAirTimer_ += timeStep;
  88. else
  89. inAirTimer_ = 0.0f;
  90. // When character has been in air less than 1/10 second, it's still interpreted as being on ground
  91. bool softGrounded = inAirTimer_ < INAIR_THRESHOLD_TIME;
  92. // Update movement & animation
  93. const Quaternion& rot = node_->GetRotation();
  94. Vector3 moveDir = Vector3::ZERO;
  95. const Vector3& velocity = body->GetLinearVelocity();
  96. // Velocity on the XZ plane
  97. Vector3 planeVelocity(velocity.x_, 0.0f, velocity.z_);
  98. if (controls_.IsDown(CTRL_FORWARD))
  99. moveDir += Vector3::FORWARD;
  100. if (controls_.IsDown(CTRL_BACK))
  101. moveDir += Vector3::BACK;
  102. if (controls_.IsDown(CTRL_LEFT))
  103. moveDir += Vector3::LEFT;
  104. if (controls_.IsDown(CTRL_RIGHT))
  105. moveDir += Vector3::RIGHT;
  106. // Normalize move vector so that diagonal strafing is not faster
  107. if (moveDir.LengthSquared() > 0.0f)
  108. moveDir.Normalize();
  109. // If in air, allow control, but slower than when on ground
  110. body->ApplyImpulse(rot * moveDir * (softGrounded ? MOVE_FORCE : INAIR_MOVE_FORCE));
  111. if (softGrounded)
  112. {
  113. // When on ground, apply a braking force to limit maximum ground velocity
  114. Vector3 brakeForce = -planeVelocity * BRAKE_FORCE;
  115. body->ApplyImpulse(brakeForce);
  116. // Jump. Must release jump control inbetween jumps
  117. if (controls_.IsDown(CTRL_JUMP))
  118. {
  119. if (okToJump_)
  120. {
  121. body->ApplyImpulse(Vector3::UP * JUMP_FORCE);
  122. okToJump_ = false;
  123. }
  124. }
  125. else
  126. okToJump_ = true;
  127. }
  128. // Play walk animation if moving on ground, otherwise fade it out
  129. if (softGrounded && !moveDir.Equals(Vector3::ZERO))
  130. animCtrl->PlayExclusive("Models/Jack_Walk.ani", 0, true, 0.2f);
  131. else
  132. animCtrl->Stop("Models/Jack_Walk.ani", 0.2f);
  133. // Set walk animation speed proportional to velocity
  134. animCtrl->SetSpeed("Models/Jack_Walk.ani", planeVelocity.Length() * 0.3f);
  135. // Reset grounded flag for next frame
  136. onGround_ = false;
  137. }