Urho2DPhysicsRope.cpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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/CoreEvents.h>
  23. #include <Urho3D/Engine/Engine.h>
  24. #include <Urho3D/Graphics/Camera.h>
  25. #include <Urho3D/Graphics/DebugRenderer.h>
  26. #include <Urho3D/Graphics/Graphics.h>
  27. #include <Urho3D/Graphics/Octree.h>
  28. #include <Urho3D/Graphics/Renderer.h>
  29. #include <Urho3D/Input/Input.h>
  30. #include <Urho3D/Scene/Scene.h>
  31. #include <Urho3D/Scene/SceneEvents.h>
  32. #include <Urho3D/UI/Font.h>
  33. #include <Urho3D/UI/Text.h>
  34. #include <Urho3D/Urho2D/CollisionBox2D.h>
  35. #include <Urho3D/Urho2D/CollisionEdge2D.h>
  36. #include <Urho3D/Urho2D/ConstraintRevolute2D.h>
  37. #include <Urho3D/Urho2D/ConstraintRope2D.h>
  38. #include <Urho3D/Urho2D/PhysicsWorld2D.h>
  39. #include <Urho3D/Urho2D/RigidBody2D.h>
  40. #include "Urho2DPhysicsRope.h"
  41. #include <Urho3D/DebugNew.h>
  42. URHO3D_DEFINE_APPLICATION_MAIN(Urho2DPhysicsRope)
  43. static const unsigned NUM_OBJECTS = 10;
  44. Urho2DPhysicsRope::Urho2DPhysicsRope(Context* context) :
  45. Sample(context)
  46. {
  47. }
  48. void Urho2DPhysicsRope::Start()
  49. {
  50. // Execute base class startup
  51. Sample::Start();
  52. // Create the scene content
  53. CreateScene();
  54. // Create the UI content
  55. CreateInstructions();
  56. // Setup the viewport for displaying the scene
  57. SetupViewport();
  58. // Hook up to the frame update events
  59. SubscribeToEvents();
  60. // Set the mouse mode to use in the sample
  61. Sample::InitMouseMode(MM_FREE);
  62. }
  63. void Urho2DPhysicsRope::CreateScene()
  64. {
  65. scene_ = new Scene(context_);
  66. scene_->CreateComponent<Octree>();
  67. scene_->CreateComponent<DebugRenderer>();
  68. // Create camera node
  69. cameraNode_ = scene_->CreateChild("Camera");
  70. // Set camera's position
  71. cameraNode_->SetPosition(Vector3(0.0f, 5.0f, -10.0f));
  72. Camera* camera = cameraNode_->CreateComponent<Camera>();
  73. camera->SetOrthographic(true);
  74. Graphics* graphics = GetSubsystem<Graphics>();
  75. camera->SetOrthoSize((float)graphics->GetHeight() * 0.05f);
  76. camera->SetZoom(1.5f * Min((float)graphics->GetWidth() / 1280.0f, (float)graphics->GetHeight() / 800.0f)); // Set zoom according to user's resolution to ensure full visibility (initial zoom (1.5) is set for full visibility at 1280x800 resolution)
  77. // Create 2D physics world component
  78. PhysicsWorld2D* physicsWorld = scene_->CreateComponent<PhysicsWorld2D>();
  79. physicsWorld->SetDrawJoint(true);
  80. // Create ground
  81. Node* groundNode = scene_->CreateChild("Ground");
  82. // Create 2D rigid body for gound
  83. RigidBody2D* groundBody = groundNode->CreateComponent<RigidBody2D>();
  84. // Create edge collider for ground
  85. CollisionEdge2D* groundShape = groundNode->CreateComponent<CollisionEdge2D>();
  86. groundShape->SetVertices(Vector2(-40.0f, 0.0f), Vector2(40.0f, 0.0f));
  87. const float y = 15.0f;
  88. RigidBody2D* prevBody = groundBody;
  89. for (unsigned i = 0; i < NUM_OBJECTS; ++i)
  90. {
  91. Node* node = scene_->CreateChild("RigidBody");
  92. // Create rigid body
  93. RigidBody2D* body = node->CreateComponent<RigidBody2D>();
  94. body->SetBodyType(BT_DYNAMIC);
  95. // Create box
  96. CollisionBox2D* box = node->CreateComponent<CollisionBox2D>();
  97. // Set friction
  98. box->SetFriction(0.2f);
  99. // Set mask bits.
  100. box->SetMaskBits(0xFFFF & ~0x0002);
  101. if (i == NUM_OBJECTS - 1)
  102. {
  103. node->SetPosition(Vector3(1.0f * i, y, 0.0f));
  104. body->SetAngularDamping(0.4f);
  105. box->SetSize(3.0f, 3.0f);
  106. box->SetDensity(100.0f);
  107. box->SetCategoryBits(0x0002);
  108. }
  109. else
  110. {
  111. node->SetPosition(Vector3(0.5f + 1.0f * i, y, 0.0f));
  112. box->SetSize(1.0f, 0.25f);
  113. box->SetDensity(20.0f);
  114. box->SetCategoryBits(0x0001);
  115. }
  116. ConstraintRevolute2D* joint = node->CreateComponent<ConstraintRevolute2D>();
  117. joint->SetOtherBody(prevBody);
  118. joint->SetAnchor(Vector2(float(i), y));
  119. joint->SetCollideConnected(false);
  120. prevBody = body;
  121. }
  122. ConstraintRope2D* constraintRope = groundNode->CreateComponent<ConstraintRope2D>();
  123. constraintRope->SetOtherBody(prevBody);
  124. constraintRope->SetOwnerBodyAnchor(Vector2(0.0f, y));
  125. constraintRope->SetMaxLength(NUM_OBJECTS - 1.0f + 0.01f);
  126. }
  127. void Urho2DPhysicsRope::CreateInstructions()
  128. {
  129. ResourceCache* cache = GetSubsystem<ResourceCache>();
  130. UI* ui = GetSubsystem<UI>();
  131. // Construct new Text object, set string to display and font to use
  132. Text* instructionText = ui->GetRoot()->CreateChild<Text>();
  133. instructionText->SetText("Use WASD keys and mouse/touch to move, Use PageUp PageDown to zoom.");
  134. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  135. // Position the text relative to the screen center
  136. instructionText->SetHorizontalAlignment(HA_CENTER);
  137. instructionText->SetVerticalAlignment(VA_CENTER);
  138. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  139. }
  140. void Urho2DPhysicsRope::SetupViewport()
  141. {
  142. Renderer* renderer = GetSubsystem<Renderer>();
  143. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  144. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  145. renderer->SetViewport(0, viewport);
  146. }
  147. void Urho2DPhysicsRope::MoveCamera(float timeStep)
  148. {
  149. // Do not move if the UI has a focused element (the console)
  150. if (GetSubsystem<UI>()->GetFocusElement())
  151. return;
  152. Input* input = GetSubsystem<Input>();
  153. // Movement speed as world units per second
  154. const float MOVE_SPEED = 4.0f;
  155. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  156. if (input->GetKeyDown(KEY_W))
  157. cameraNode_->Translate(Vector3::UP * MOVE_SPEED * timeStep);
  158. if (input->GetKeyDown(KEY_S))
  159. cameraNode_->Translate(Vector3::DOWN * MOVE_SPEED * timeStep);
  160. if (input->GetKeyDown(KEY_A))
  161. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  162. if (input->GetKeyDown(KEY_D))
  163. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  164. if (input->GetKeyDown(KEY_PAGEUP))
  165. {
  166. Camera* camera = cameraNode_->GetComponent<Camera>();
  167. camera->SetZoom(camera->GetZoom() * 1.01f);
  168. }
  169. if (input->GetKeyDown(KEY_PAGEDOWN))
  170. {
  171. Camera* camera = cameraNode_->GetComponent<Camera>();
  172. camera->SetZoom(camera->GetZoom() * 0.99f);
  173. }
  174. }
  175. void Urho2DPhysicsRope::SubscribeToEvents()
  176. {
  177. // Subscribe HandleUpdate() function for processing update events
  178. SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(Urho2DPhysicsRope, HandleUpdate));
  179. // Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample
  180. UnsubscribeFromEvent(E_SCENEUPDATE);
  181. }
  182. void Urho2DPhysicsRope::HandleUpdate(StringHash eventType, VariantMap& eventData)
  183. {
  184. using namespace Update;
  185. // Take the frame time step, which is stored as a float
  186. float timeStep = eventData[P_TIMESTEP].GetFloat();
  187. // Move the camera, scale movement with time step
  188. MoveCamera(timeStep);
  189. PhysicsWorld2D* physicsWorld = scene_->GetComponent<PhysicsWorld2D>();
  190. physicsWorld->DrawDebugGeometry();
  191. }