Vehicle.cpp 8.7 KB

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