Vehicle.cpp 7.4 KB

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