24_Urho2DSprite.as 8.7 KB

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