Urho2DPhysics.cpp 8.3 KB

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