24_Urho2DSprite.as 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. // Urho2D sprite example.
  2. // This sample demonstrates:
  3. // - Creating a 2D scene with sprite
  4. // - Displaying the scene using the Renderer subsystem
  5. // - Handling keyboard to move and zoom 2D camera
  6. #include "Scripts/Utilities/Sample.as"
  7. Array<Node@> spriteNodes;
  8. void Start()
  9. {
  10. // Execute the common startup for samples
  11. SampleStart();
  12. // Create the scene content
  13. CreateScene();
  14. // Create the UI content
  15. CreateInstructions();
  16. // Setup the viewport for displaying the scene
  17. SetupViewport();
  18. // Set the mouse mode to use in the sample
  19. SampleInitMouseMode(MM_FREE);
  20. // Hook up to the frame update events
  21. SubscribeToEvents();
  22. }
  23. void CreateScene()
  24. {
  25. scene_ = Scene();
  26. // Create the Octree component to the scene. This is required before adding any drawable components, or else nothing will
  27. // show up. The default octree volume will be from (-1000, -1000, -1000) to (1000, 1000, 1000) in world coordinates; it
  28. // is also legal to place objects outside the volume but their visibility can then not be checked in a hierarchically
  29. // optimizing manner
  30. scene_.CreateComponent("Octree");
  31. // Create a scene node for the camera, which we will move around
  32. // The camera will use default settings (1000 far clip distance, 45 degrees FOV, set aspect ratio automatically)
  33. cameraNode = scene_.CreateChild("Camera");
  34. // Set an initial position for the camera scene node above the plane
  35. cameraNode.position = Vector3(0.0f, 0.0f, -10.0f);
  36. Camera@ camera = cameraNode.CreateComponent("Camera");
  37. camera.orthographic = true;
  38. camera.orthoSize = graphics.height * PIXEL_SIZE;
  39. Sprite2D@ sprite = cache.GetResource("Sprite2D", "Urho2D/Aster.png");
  40. if (sprite is null)
  41. return;
  42. uint halfWidth = uint(graphics.width * PIXEL_SIZE * 0.5f);
  43. uint halfHeight = uint(graphics.height * PIXEL_SIZE * 0.5f);
  44. // Create more StaticModel objects to the scene, randomly positioned, rotated and scaled. For rotation, we construct a
  45. // quaternion from Euler angles where the Y angle (rotation about the Y axis) is randomized. The mushroom model contains
  46. // LOD levels, so the StaticModel component will automatically select the LOD level according to the view distance (you'll
  47. // see the model get simpler as it moves further away). Finally, rendering a large number of the same object with the
  48. // same material allows instancing to be used, if the GPU supports it. This reduces the amount of CPU work in rendering the
  49. // scene.
  50. const uint NUM_SPRITES = 200;
  51. for (uint i = 0; i < NUM_SPRITES; ++i)
  52. {
  53. Node@ spriteNode = scene_.CreateChild("StaticSprite2D");
  54. spriteNode.position = Vector3(Random(-halfWidth, halfWidth), Random(-halfHeight, halfHeight), 0.0f);
  55. StaticSprite2D@ staticSprite = spriteNode.CreateComponent("StaticSprite2D");
  56. // Set color
  57. staticSprite.color = Color(Random(1.0f), Random(1.0f), Random(1.0f), 1.0f);
  58. // Set blend mode
  59. staticSprite.blendMode = BLEND_ALPHA;
  60. // Set sprite
  61. staticSprite.sprite = sprite;
  62. spriteNode.vars["MoveSpeed"] = Vector3(Random(-2.0f, 2.0f), Random(-2.0f, 2.0f), 0.0f);
  63. spriteNode.vars["RotateSpeed"] = Random(-90.0f, 90.0f);
  64. spriteNodes.Push(spriteNode);
  65. }
  66. AnimationSet2D@ animationSet = cache.GetResource("AnimationSet2D", "Urho2D/GoldIcon.scml");
  67. if (animationSet is null)
  68. return;
  69. Node@ spriteNode = scene_.CreateChild("AnimatedSprite2D");
  70. spriteNode.position = Vector3(0.0f, 0.0f, -1.0f);
  71. AnimatedSprite2D@ animatedSprite = spriteNode.CreateComponent("AnimatedSprite2D");
  72. // Set animation
  73. animatedSprite.animationSet = animationSet;
  74. animatedSprite.animation = "idle";
  75. }
  76. void CreateInstructions()
  77. {
  78. // Construct new Text object, set string to display and font to use
  79. Text@ instructionText = ui.root.CreateChild("Text");
  80. instructionText.text = "Use WASD keys and mouse to move, Use PageUp PageDown to zoom.";
  81. instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15);
  82. // Position the text relative to the screen center
  83. instructionText.horizontalAlignment = HA_CENTER;
  84. instructionText.verticalAlignment = VA_CENTER;
  85. instructionText.SetPosition(0, ui.root.height / 4);
  86. }
  87. void SetupViewport()
  88. {
  89. // 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
  90. // at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward / deferred) to
  91. // use, but now we just use full screen and default render path configured in the engine command line options
  92. Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera"));
  93. renderer.viewports[0] = viewport;
  94. }
  95. void MoveCamera(float timeStep)
  96. {
  97. // Do not move if the UI has a focused element (the console)
  98. if (ui.focusElement !is null)
  99. return;
  100. // Movement speed as world units per second
  101. const float MOVE_SPEED = 4.0f;
  102. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  103. if (input.keyDown[KEY_W])
  104. cameraNode.Translate(Vector3::UP * MOVE_SPEED * timeStep);
  105. if (input.keyDown[KEY_S])
  106. cameraNode.Translate(Vector3::DOWN * MOVE_SPEED * timeStep);
  107. if (input.keyDown[KEY_A])
  108. cameraNode.Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  109. if (input.keyDown[KEY_D])
  110. cameraNode.Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  111. if (input.keyDown[KEY_PAGEUP])
  112. {
  113. Camera@ camera = cameraNode.GetComponent("Camera");
  114. camera.zoom = camera.zoom * 1.01f;
  115. }
  116. if (input.keyDown[KEY_PAGEDOWN])
  117. {
  118. Camera@ camera = cameraNode.GetComponent("Camera");
  119. camera.zoom = camera.zoom * 0.99f;
  120. }
  121. }
  122. void SubscribeToEvents()
  123. {
  124. // Subscribe HandleUpdate() function for processing update events
  125. SubscribeToEvent("Update", "HandleUpdate");
  126. // Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample
  127. UnsubscribeFromEvent("SceneUpdate");
  128. }
  129. void HandleUpdate(StringHash eventType, VariantMap& eventData)
  130. {
  131. // Take the frame time step, which is stored as a float
  132. float timeStep = eventData["TimeStep"].GetFloat();
  133. // Move the camera, scale movement with time step
  134. MoveCamera(timeStep);
  135. float halfWidth = graphics.width * 0.5f * PIXEL_SIZE;
  136. float halfHeight = graphics.height * 0.5f * PIXEL_SIZE;
  137. // Go through all sprites
  138. for (uint i = 0; i < spriteNodes.length; ++i)
  139. {
  140. Node@ spriteNode = spriteNodes[i];
  141. Vector3 moveSpeed = spriteNode.vars["MoveSpeed"].GetVector3();
  142. Vector3 newPosition = spriteNode.position + moveSpeed * timeStep;
  143. if (newPosition.x < -halfWidth || newPosition.x > halfWidth)
  144. {
  145. newPosition.x = spriteNode.position.x;
  146. moveSpeed.x = -moveSpeed.x;
  147. spriteNode.vars["MoveSpeed"] = moveSpeed;
  148. }
  149. if (newPosition.y < -halfHeight || newPosition.y > halfHeight)
  150. {
  151. newPosition.y = spriteNode.position.y;
  152. moveSpeed.y = -moveSpeed.y;
  153. spriteNode.vars["MoveSpeed"] = moveSpeed;
  154. }
  155. spriteNode.position = newPosition;
  156. spriteNode.Roll(spriteNode.vars["RotateSpeed"].GetFloat() * timeStep);
  157. }
  158. }
  159. // Create XML patch instructions for screen joystick layout specific to this sample app
  160. String patchInstructions =
  161. "<patch>" +
  162. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" +
  163. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Zoom In</replace>" +
  164. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" +
  165. " <element type=\"Text\">" +
  166. " <attribute name=\"Name\" value=\"KeyBinding\" />" +
  167. " <attribute name=\"Text\" value=\"PAGEUP\" />" +
  168. " </element>" +
  169. " </add>" +
  170. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" +
  171. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Zoom Out</replace>" +
  172. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" +
  173. " <element type=\"Text\">" +
  174. " <attribute name=\"Name\" value=\"KeyBinding\" />" +
  175. " <attribute name=\"Text\" value=\"PAGEDOWN\" />" +
  176. " </element>" +
  177. " </add>" +
  178. "</patch>";