Urho2DPhysics.cpp 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. // Copyright (c) 2008-2023 the Urho3D project
  2. // License: MIT
  3. #include <Urho3D/Core/CoreEvents.h>
  4. #include <Urho3D/Engine/Engine.h>
  5. #include <Urho3D/Graphics/Camera.h>
  6. #include <Urho3D/Graphics/DebugRenderer.h>
  7. #include <Urho3D/Graphics/Graphics.h>
  8. #include <Urho3D/Graphics/Octree.h>
  9. #include <Urho3D/Graphics/Renderer.h>
  10. #include <Urho3D/Input/Input.h>
  11. #include <Urho3D/Physics2D/CollisionBox2D.h>
  12. #include <Urho3D/Physics2D/CollisionCircle2D.h>
  13. #include <Urho3D/Physics2D/PhysicsWorld2D.h>
  14. #include <Urho3D/Physics2D/RigidBody2D.h>
  15. #include <Urho3D/Resource/ResourceCache.h>
  16. #include <Urho3D/Scene/Scene.h>
  17. #include <Urho3D/Scene/SceneEvents.h>
  18. #include <Urho3D/UI/Font.h>
  19. #include <Urho3D/UI/Text.h>
  20. #include <Urho3D/Urho2D/Drawable2D.h>
  21. #include <Urho3D/Urho2D/Sprite2D.h>
  22. #include <Urho3D/Urho2D/StaticSprite2D.h>
  23. #include "Urho2DPhysics.h"
  24. #include <Urho3D/DebugNew.h>
  25. URHO3D_DEFINE_APPLICATION_MAIN(Urho2DPhysics)
  26. static const unsigned NUM_OBJECTS = 100;
  27. Urho2DPhysics::Urho2DPhysics(Context* context) :
  28. Sample(context)
  29. {
  30. }
  31. void Urho2DPhysics::Start()
  32. {
  33. // Execute base class startup
  34. Sample::Start();
  35. // Create the scene content
  36. CreateScene();
  37. // Create the UI content
  38. CreateInstructions();
  39. // Setup the viewport for displaying the scene
  40. SetupViewport();
  41. // Hook up to the frame update events
  42. SubscribeToEvents();
  43. // Set the mouse mode to use in the sample
  44. Sample::InitMouseMode(MM_FREE);
  45. }
  46. void Urho2DPhysics::CreateScene()
  47. {
  48. scene_ = new Scene(context_);
  49. scene_->CreateComponent<Octree>();
  50. scene_->CreateComponent<DebugRenderer>();
  51. // Create camera node
  52. cameraNode_ = scene_->CreateChild("Camera");
  53. // Set camera's position
  54. cameraNode_->SetPosition(Vector3(0.0f, 0.0f, -10.0f));
  55. auto* camera = cameraNode_->CreateComponent<Camera>();
  56. camera->SetOrthographic(true);
  57. auto* graphics = GetSubsystem<Graphics>();
  58. camera->SetOrthoSize((float)graphics->GetHeight() * PIXEL_SIZE);
  59. camera->SetZoom(1.2f * 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.2) is set for full visibility at 1280x800 resolution)
  60. // Create 2D physics world component
  61. /*PhysicsWorld2D* physicsWorld = */scene_->CreateComponent<PhysicsWorld2D>();
  62. auto* cache = GetSubsystem<ResourceCache>();
  63. auto* boxSprite = cache->GetResource<Sprite2D>("Urho2D/Box.png");
  64. auto* ballSprite = cache->GetResource<Sprite2D>("Urho2D/Ball.png");
  65. // Create ground.
  66. Node* groundNode = scene_->CreateChild("Ground");
  67. groundNode->SetPosition(Vector3(0.0f, -3.0f, 0.0f));
  68. groundNode->SetScale(Vector3(200.0f, 1.0f, 0.0f));
  69. // Create 2D rigid body for gound
  70. /*RigidBody2D* groundBody = */groundNode->CreateComponent<RigidBody2D>();
  71. auto* groundSprite = groundNode->CreateComponent<StaticSprite2D>();
  72. groundSprite->SetSprite(boxSprite);
  73. // Create box collider for ground
  74. auto* groundShape = groundNode->CreateComponent<CollisionBox2D>();
  75. // Set box size
  76. groundShape->SetSize(Vector2(0.32f, 0.32f));
  77. // Set friction
  78. groundShape->SetFriction(0.5f);
  79. for (unsigned i = 0; i < NUM_OBJECTS; ++i)
  80. {
  81. Node* node = scene_->CreateChild("RigidBody");
  82. node->SetPosition(Vector3(Random(-0.1f, 0.1f), 5.0f + i * 0.4f, 0.0f));
  83. // Create rigid body
  84. auto* body = node->CreateComponent<RigidBody2D>();
  85. body->SetBodyType(BT_DYNAMIC);
  86. auto* staticSprite = node->CreateComponent<StaticSprite2D>();
  87. if (i % 2 == 0)
  88. {
  89. staticSprite->SetSprite(boxSprite);
  90. // Create box
  91. auto* box = node->CreateComponent<CollisionBox2D>();
  92. // Set size
  93. box->SetSize(Vector2(0.32f, 0.32f));
  94. // Set density
  95. box->SetDensity(1.0f);
  96. // Set friction
  97. box->SetFriction(0.5f);
  98. // Set restitution
  99. box->SetRestitution(0.1f);
  100. }
  101. else
  102. {
  103. staticSprite->SetSprite(ballSprite);
  104. // Create circle
  105. auto* circle = node->CreateComponent<CollisionCircle2D>();
  106. // Set radius
  107. circle->SetRadius(0.16f);
  108. // Set density
  109. circle->SetDensity(1.0f);
  110. // Set friction.
  111. circle->SetFriction(0.5f);
  112. // Set restitution
  113. circle->SetRestitution(0.1f);
  114. }
  115. }
  116. }
  117. void Urho2DPhysics::CreateInstructions()
  118. {
  119. auto* cache = GetSubsystem<ResourceCache>();
  120. auto* ui = GetSubsystem<UI>();
  121. // Construct new Text object, set string to display and font to use
  122. auto* instructionText = ui->GetRoot()->CreateChild<Text>();
  123. instructionText->SetText("Use WASD keys to move, use PageUp PageDown keys to zoom.");
  124. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  125. // Position the text relative to the screen center
  126. instructionText->SetHorizontalAlignment(HA_CENTER);
  127. instructionText->SetVerticalAlignment(VA_CENTER);
  128. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  129. }
  130. void Urho2DPhysics::SetupViewport()
  131. {
  132. auto* renderer = GetSubsystem<Renderer>();
  133. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  134. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  135. renderer->SetViewport(0, viewport);
  136. }
  137. void Urho2DPhysics::MoveCamera(float timeStep)
  138. {
  139. // Do not move if the UI has a focused element (the console)
  140. if (GetSubsystem<UI>()->GetFocusElement())
  141. return;
  142. auto* input = GetSubsystem<Input>();
  143. // Movement speed as world units per second
  144. const float MOVE_SPEED = 4.0f;
  145. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  146. if (input->GetKeyDown(KEY_W))
  147. cameraNode_->Translate(Vector3::UP * MOVE_SPEED * timeStep);
  148. if (input->GetKeyDown(KEY_S))
  149. cameraNode_->Translate(Vector3::DOWN * MOVE_SPEED * timeStep);
  150. if (input->GetKeyDown(KEY_A))
  151. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  152. if (input->GetKeyDown(KEY_D))
  153. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  154. if (input->GetKeyDown(KEY_PAGEUP))
  155. {
  156. auto* camera = cameraNode_->GetComponent<Camera>();
  157. camera->SetZoom(camera->GetZoom() * 1.01f);
  158. }
  159. if (input->GetKeyDown(KEY_PAGEDOWN))
  160. {
  161. auto* camera = cameraNode_->GetComponent<Camera>();
  162. camera->SetZoom(camera->GetZoom() * 0.99f);
  163. }
  164. }
  165. void Urho2DPhysics::SubscribeToEvents()
  166. {
  167. // Subscribe HandleUpdate() function for processing update events
  168. SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(Urho2DPhysics, HandleUpdate));
  169. // Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample
  170. UnsubscribeFromEvent(E_SCENEUPDATE);
  171. }
  172. void Urho2DPhysics::HandleUpdate(StringHash eventType, VariantMap& eventData)
  173. {
  174. using namespace Update;
  175. // Take the frame time step, which is stored as a float
  176. float timeStep = eventData[P_TIMESTEP].GetFloat();
  177. // Move the camera, scale movement with time step
  178. MoveCamera(timeStep);
  179. }