Vehicle.cpp 8.8 KB

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