Vehicle.cpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. //
  2. // Copyright (c) 2008-2017 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 <Urho3D/Core/Context.h>
  23. #include <Urho3D/Graphics/Material.h>
  24. #include <Urho3D/Graphics/Model.h>
  25. #include <Urho3D/Graphics/StaticModel.h>
  26. #include <Urho3D/Physics/CollisionShape.h>
  27. #include <Urho3D/Physics/Constraint.h>
  28. #include <Urho3D/Physics/PhysicsEvents.h>
  29. #include <Urho3D/Physics/PhysicsWorld.h>
  30. #include <Urho3D/Physics/RigidBody.h>
  31. #include <Urho3D/Resource/ResourceCache.h>
  32. #include <Urho3D/Scene/Scene.h>
  33. #include "Vehicle.h"
  34. Vehicle::Vehicle(Context* context) :
  35. LogicComponent(context),
  36. steering_(0.0f)
  37. {
  38. // Only the physics update event is needed: unsubscribe from the rest for optimization
  39. SetUpdateEventMask(USE_FIXEDUPDATE);
  40. }
  41. void Vehicle::RegisterObject(Context* context)
  42. {
  43. context->RegisterFactory<Vehicle>();
  44. URHO3D_ATTRIBUTE("Controls Yaw", float, controls_.yaw_, 0.0f, AM_DEFAULT);
  45. URHO3D_ATTRIBUTE("Controls Pitch", float, controls_.pitch_, 0.0f, AM_DEFAULT);
  46. URHO3D_ATTRIBUTE("Steering", float, steering_, 0.0f, AM_DEFAULT);
  47. // Register wheel node IDs as attributes so that the wheel nodes can be reaquired on deserialization. They need to be tagged
  48. // as node ID's so that the deserialization code knows to rewrite the IDs in case they are different on load than on save
  49. URHO3D_ATTRIBUTE("Front Left Node", unsigned, frontLeftID_, 0, AM_DEFAULT | AM_NODEID);
  50. URHO3D_ATTRIBUTE("Front Right Node", unsigned, frontRightID_, 0, AM_DEFAULT | AM_NODEID);
  51. URHO3D_ATTRIBUTE("Rear Left Node", unsigned, rearLeftID_, 0, AM_DEFAULT | AM_NODEID);
  52. URHO3D_ATTRIBUTE("Rear Right Node", unsigned, rearRightID_, 0, AM_DEFAULT | AM_NODEID);
  53. }
  54. void Vehicle::ApplyAttributes()
  55. {
  56. // This function is called on each Serializable after the whole scene has been loaded. Reacquire wheel nodes from ID's
  57. // as well as all required physics components
  58. Scene* scene = GetScene();
  59. frontLeft_ = scene->GetNode(frontLeftID_);
  60. frontRight_ = scene->GetNode(frontRightID_);
  61. rearLeft_ = scene->GetNode(rearLeftID_);
  62. rearRight_ = scene->GetNode(rearRightID_);
  63. hullBody_ = node_->GetComponent<RigidBody>();
  64. GetWheelComponents();
  65. }
  66. void Vehicle::FixedUpdate(float timeStep)
  67. {
  68. float newSteering = 0.0f;
  69. float accelerator = 0.0f;
  70. // Read controls
  71. if (controls_.buttons_ & CTRL_LEFT)
  72. newSteering = -1.0f;
  73. if (controls_.buttons_ & CTRL_RIGHT)
  74. newSteering = 1.0f;
  75. if (controls_.buttons_ & CTRL_FORWARD)
  76. accelerator = 1.0f;
  77. if (controls_.buttons_ & CTRL_BACK)
  78. accelerator = -0.5f;
  79. // When steering, wake up the wheel rigidbodies so that their orientation is updated
  80. if (newSteering != 0.0f)
  81. {
  82. frontLeftBody_->Activate();
  83. frontRightBody_->Activate();
  84. steering_ = steering_ * 0.95f + newSteering * 0.05f;
  85. }
  86. else
  87. steering_ = steering_ * 0.8f + newSteering * 0.2f;
  88. // Set front wheel angles
  89. Quaternion steeringRot(0, steering_ * MAX_WHEEL_ANGLE, 0);
  90. frontLeftAxis_->SetOtherAxis(steeringRot * Vector3::LEFT);
  91. frontRightAxis_->SetOtherAxis(steeringRot * Vector3::RIGHT);
  92. Quaternion hullRot = hullBody_->GetRotation();
  93. if (accelerator != 0.0f)
  94. {
  95. // Torques are applied in world space, so need to take the vehicle & wheel rotation into account
  96. Vector3 torqueVec = Vector3(ENGINE_POWER * accelerator, 0.0f, 0.0f);
  97. frontLeftBody_->ApplyTorque(hullRot * steeringRot * torqueVec);
  98. frontRightBody_->ApplyTorque(hullRot * steeringRot * torqueVec);
  99. rearLeftBody_->ApplyTorque(hullRot * torqueVec);
  100. rearRightBody_->ApplyTorque(hullRot * torqueVec);
  101. }
  102. // Apply downforce proportional to velocity
  103. Vector3 localVelocity = hullRot.Inverse() * hullBody_->GetLinearVelocity();
  104. hullBody_->ApplyForce(hullRot * Vector3::DOWN * Abs(localVelocity.z_) * DOWN_FORCE);
  105. }
  106. void Vehicle::Init()
  107. {
  108. // This function is called only from the main program when initially creating the vehicle, not on scene load
  109. auto* cache = GetSubsystem<ResourceCache>();
  110. auto* hullObject = node_->CreateComponent<StaticModel>();
  111. hullBody_ = node_->CreateComponent<RigidBody>();
  112. auto* hullShape = node_->CreateComponent<CollisionShape>();
  113. node_->SetScale(Vector3(1.5f, 1.0f, 3.0f));
  114. hullObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  115. hullObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  116. hullObject->SetCastShadows(true);
  117. hullShape->SetBox(Vector3::ONE);
  118. hullBody_->SetMass(4.0f);
  119. hullBody_->SetLinearDamping(0.2f); // Some air resistance
  120. hullBody_->SetAngularDamping(0.5f);
  121. hullBody_->SetCollisionLayer(1);
  122. InitWheel("FrontLeft", Vector3(-0.6f, -0.4f, 0.3f), frontLeft_, frontLeftID_);
  123. InitWheel("FrontRight", Vector3(0.6f, -0.4f, 0.3f), frontRight_, frontRightID_);
  124. InitWheel("RearLeft", Vector3(-0.6f, -0.4f, -0.3f), rearLeft_, rearLeftID_);
  125. InitWheel("RearRight", Vector3(0.6f, -0.4f, -0.3f), rearRight_, rearRightID_);
  126. GetWheelComponents();
  127. }
  128. void Vehicle::InitWheel(const String& name, const Vector3& offset, WeakPtr<Node>& wheelNode, unsigned& wheelNodeID)
  129. {
  130. auto* cache = GetSubsystem<ResourceCache>();
  131. // Note: do not parent the wheel to the hull scene node. Instead create it on the root level and let the physics
  132. // constraint keep it together
  133. wheelNode = GetScene()->CreateChild(name);
  134. wheelNode->SetPosition(node_->LocalToWorld(offset));
  135. wheelNode->SetRotation(node_->GetRotation() * (offset.x_ >= 0.0 ? Quaternion(0.0f, 0.0f, -90.0f) :
  136. Quaternion(0.0f, 0.0f, 90.0f)));
  137. wheelNode->SetScale(Vector3(0.8f, 0.5f, 0.8f));
  138. // Remember the ID for serialization
  139. wheelNodeID = wheelNode->GetID();
  140. auto* wheelObject = wheelNode->CreateComponent<StaticModel>();
  141. auto* wheelBody = wheelNode->CreateComponent<RigidBody>();
  142. auto* wheelShape = wheelNode->CreateComponent<CollisionShape>();
  143. auto* wheelConstraint = wheelNode->CreateComponent<Constraint>();
  144. wheelObject->SetModel(cache->GetResource<Model>("Models/Cylinder.mdl"));
  145. wheelObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  146. wheelObject->SetCastShadows(true);
  147. wheelShape->SetSphere(1.0f);
  148. wheelBody->SetFriction(1.0f);
  149. wheelBody->SetMass(1.0f);
  150. wheelBody->SetLinearDamping(0.2f); // Some air resistance
  151. wheelBody->SetAngularDamping(0.75f); // Could also use rolling friction
  152. wheelBody->SetCollisionLayer(1);
  153. wheelConstraint->SetConstraintType(CONSTRAINT_HINGE);
  154. wheelConstraint->SetOtherBody(GetComponent<RigidBody>()); // Connect to the hull body
  155. wheelConstraint->SetWorldPosition(wheelNode->GetPosition()); // Set constraint's both ends at wheel's location
  156. wheelConstraint->SetAxis(Vector3::UP); // Wheel rotates around its local Y-axis
  157. wheelConstraint->SetOtherAxis(offset.x_ >= 0.0 ? Vector3::RIGHT : Vector3::LEFT); // Wheel's hull axis points either left or right
  158. wheelConstraint->SetLowLimit(Vector2(-180.0f, 0.0f)); // Let the wheel rotate freely around the axis
  159. wheelConstraint->SetHighLimit(Vector2(180.0f, 0.0f));
  160. wheelConstraint->SetDisableCollision(true); // Let the wheel intersect the vehicle hull
  161. }
  162. void Vehicle::GetWheelComponents()
  163. {
  164. frontLeftAxis_ = frontLeft_->GetComponent<Constraint>();
  165. frontRightAxis_ = frontRight_->GetComponent<Constraint>();
  166. frontLeftBody_ = frontLeft_->GetComponent<RigidBody>();
  167. frontRightBody_ = frontRight_->GetComponent<RigidBody>();
  168. rearLeftBody_ = rearLeft_->GetComponent<RigidBody>();
  169. rearRightBody_ = rearRight_->GetComponent<RigidBody>();
  170. }