27_Urho2DPhysics.as 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. // Urho2D physics sample.
  2. // This sample demonstrates:
  3. // - Creating both static and moving 2D physics objects to a scene
  4. // - Displaying physics debug geometry
  5. #include "Scripts/Utilities/Sample.as"
  6. void Start()
  7. {
  8. // Execute the common startup for samples
  9. SampleStart();
  10. // Create the scene content
  11. CreateScene();
  12. // Create the UI content
  13. CreateInstructions();
  14. // Setup the viewport for displaying the scene
  15. SetupViewport();
  16. // Set the mouse mode to use in the sample
  17. SampleInitMouseMode(MM_FREE);
  18. // Hook up to the frame update events
  19. SubscribeToEvents();
  20. }
  21. void CreateScene()
  22. {
  23. scene_ = Scene();
  24. // Create the Octree component to the scene. This is required before adding any drawable components, or else nothing will
  25. // show up. The default octree volume will be from (-1000, -1000, -1000) to (1000, 1000, 1000) in world coordinates; it
  26. // is also legal to place objects outside the volume but their visibility can then not be checked in a hierarchically
  27. // optimizing manner
  28. scene_.CreateComponent("Octree");
  29. scene_.CreateComponent("DebugRenderer");
  30. // Create a scene node for the camera, which we will move around
  31. // The camera will use default settings (1000 far clip distance, 45 degrees FOV, set aspect ratio automatically)
  32. cameraNode = scene_.CreateChild("Camera");
  33. // Set an initial position for the camera scene node above the plane
  34. cameraNode.position = Vector3(0.0f, 0.0f, -10.0f);
  35. Camera@ camera = cameraNode.CreateComponent("Camera");
  36. camera.orthographic = true;
  37. camera.orthoSize = graphics.height * PIXEL_SIZE;
  38. camera.zoom = 1.2f * Min(graphics.width / 1280.0f, graphics.height / 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)
  39. // Create 2D physics world component
  40. scene_.CreateComponent("PhysicsWorld2D");
  41. Sprite2D@ boxSprite = cache.GetResource("Sprite2D", "Urho2D/Box.png");
  42. Sprite2D@ ballSprite = cache.GetResource("Sprite2D", "Urho2D/Ball.png");
  43. // Create ground.
  44. Node@ groundNode = scene_.CreateChild("Ground");
  45. groundNode.position = Vector3(0.0f, -3.0f, 0.0f);
  46. groundNode.scale = Vector3(200.0f, 1.0f, 0.0f);
  47. // Create 2D rigid body for gound
  48. RigidBody2D@ groundBody = groundNode.CreateComponent("RigidBody2D");
  49. StaticSprite2D@ groundSprite = groundNode.CreateComponent("StaticSprite2D");
  50. groundSprite.sprite = boxSprite;
  51. // Create box collider for ground
  52. CollisionBox2D@ groundShape = groundNode.CreateComponent("CollisionBox2D");
  53. // Set box size
  54. groundShape.size = Vector2(0.32f, 0.32f);
  55. // Set friction
  56. groundShape.friction = 0.5f;
  57. const uint NUM_OBJECTS = 100;
  58. for (uint i = 0; i < NUM_OBJECTS; ++i)
  59. {
  60. Node@ node = scene_.CreateChild("RigidBody");
  61. node.position = Vector3(Random(-0.1f, 0.1f), 5.0f + i * 0.4f, 0.0f);
  62. // Create rigid body
  63. RigidBody2D@ body = node.CreateComponent("RigidBody2D");
  64. body.bodyType = BT_DYNAMIC;
  65. StaticSprite2D@ staticSprite = node.CreateComponent("StaticSprite2D");
  66. if (i % 2 == 0)
  67. {
  68. staticSprite.sprite = boxSprite;
  69. // Create box
  70. CollisionBox2D@ box = node.CreateComponent("CollisionBox2D");
  71. // Set size
  72. box.size = Vector2(0.32f, 0.32f);
  73. // Set density
  74. box.density = 1.0f;
  75. // Set friction
  76. box.friction = 0.5f;
  77. // Set restitution
  78. box.restitution = 0.1f;
  79. }
  80. else
  81. {
  82. staticSprite.sprite = ballSprite;
  83. // Create circle
  84. CollisionCircle2D@ circle = node.CreateComponent("CollisionCircle2D");
  85. // Set radius
  86. circle.radius = 0.16f;
  87. // Set density
  88. circle.density = 1.0f;
  89. // Set friction.
  90. circle.friction = 0.5f;
  91. // Set restitution
  92. circle.restitution = 0.1f;
  93. }
  94. }
  95. }
  96. void CreateInstructions()
  97. {
  98. // Construct new Text object, set string to display and font to use
  99. Text@ instructionText = ui.root.CreateChild("Text");
  100. instructionText.text = "Use WASD keys and mouse to move, Use PageUp PageDown to zoom.";
  101. instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15);
  102. // Position the text relative to the screen center
  103. instructionText.horizontalAlignment = HA_CENTER;
  104. instructionText.verticalAlignment = VA_CENTER;
  105. instructionText.SetPosition(0, ui.root.height / 4);
  106. }
  107. void SetupViewport()
  108. {
  109. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen. We need to define the scene and the camera
  110. // at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward / deferred) to
  111. // use, but now we just use full screen and default render path configured in the engine command line options
  112. Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera"));
  113. renderer.viewports[0] = viewport;
  114. }
  115. void MoveCamera(float timeStep)
  116. {
  117. // Do not move if the UI has a focused element (the console)
  118. if (ui.focusElement !is null)
  119. return;
  120. // Movement speed as world units per second
  121. const float MOVE_SPEED = 4.0f;
  122. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  123. if (input.keyDown[KEY_W])
  124. cameraNode.Translate(Vector3::UP * MOVE_SPEED * timeStep);
  125. if (input.keyDown[KEY_S])
  126. cameraNode.Translate(Vector3::DOWN * MOVE_SPEED * timeStep);
  127. if (input.keyDown[KEY_A])
  128. cameraNode.Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  129. if (input.keyDown[KEY_D])
  130. cameraNode.Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  131. if (input.keyDown[KEY_PAGEUP])
  132. {
  133. Camera@ camera = cameraNode.GetComponent("Camera");
  134. camera.zoom = camera.zoom * 1.01f;
  135. }
  136. if (input.keyDown[KEY_PAGEDOWN])
  137. {
  138. Camera@ camera = cameraNode.GetComponent("Camera");
  139. camera.zoom = camera.zoom * 0.99f;
  140. }
  141. }
  142. void SubscribeToEvents()
  143. {
  144. // Subscribe HandleUpdate() function for processing update events
  145. SubscribeToEvent("Update", "HandleUpdate");
  146. // Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample
  147. UnsubscribeFromEvent("SceneUpdate");
  148. }
  149. void HandleUpdate(StringHash eventType, VariantMap& eventData)
  150. {
  151. // Take the frame time step, which is stored as a float
  152. float timeStep = eventData["TimeStep"].GetFloat();
  153. // Move the camera, scale movement with time step
  154. MoveCamera(timeStep);
  155. }
  156. // Create XML patch instructions for screen joystick layout specific to this sample app
  157. String patchInstructions =
  158. "<patch>" +
  159. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" +
  160. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Zoom In</replace>" +
  161. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" +
  162. " <element type=\"Text\">" +
  163. " <attribute name=\"Name\" value=\"KeyBinding\" />" +
  164. " <attribute name=\"Text\" value=\"PAGEUP\" />" +
  165. " </element>" +
  166. " </add>" +
  167. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" +
  168. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Zoom Out</replace>" +
  169. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" +
  170. " <element type=\"Text\">" +
  171. " <attribute name=\"Name\" value=\"KeyBinding\" />" +
  172. " <attribute name=\"Text\" value=\"PAGEDOWN\" />" +
  173. " </element>" +
  174. " </add>" +
  175. "</patch>";