27_Urho2DPhysics.as 8.0 KB

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