24_Urho2DSprite.as 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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.SetAnimation(animationSet, "idle");
  72. }
  73. void CreateInstructions()
  74. {
  75. // Construct new Text object, set string to display and font to use
  76. Text@ instructionText = ui.root.CreateChild("Text");
  77. instructionText.text = "Use WASD keys and mouse to move, Use PageUp PageDown to zoom.";
  78. instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15);
  79. // Position the text relative to the screen center
  80. instructionText.horizontalAlignment = HA_CENTER;
  81. instructionText.verticalAlignment = VA_CENTER;
  82. instructionText.SetPosition(0, ui.root.height / 4);
  83. }
  84. void SetupViewport()
  85. {
  86. // 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
  87. // at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward / deferred) to
  88. // use, but now we just use full screen and default render path configured in the engine command line options
  89. Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera"));
  90. renderer.viewports[0] = viewport;
  91. }
  92. void MoveCamera(float timeStep)
  93. {
  94. // Do not move if the UI has a focused element (the console)
  95. if (ui.focusElement !is null)
  96. return;
  97. // Movement speed as world units per second
  98. const float MOVE_SPEED = 4.0f;
  99. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  100. if (input.keyDown['W'])
  101. cameraNode.Translate(Vector3(0.0f, 1.0f, 0.0f) * MOVE_SPEED * timeStep);
  102. if (input.keyDown['S'])
  103. cameraNode.Translate(Vector3(0.0f, -1.0f, 0.0f) * MOVE_SPEED * timeStep);
  104. if (input.keyDown['A'])
  105. cameraNode.Translate(Vector3(-1.0f, 0.0f, 0.0f) * MOVE_SPEED * timeStep);
  106. if (input.keyDown['D'])
  107. cameraNode.Translate(Vector3(1.0f, 0.0f, 0.0f) * MOVE_SPEED * timeStep);
  108. if (input.keyDown[KEY_PAGEUP])
  109. {
  110. Camera@ camera = cameraNode.GetComponent("Camera");
  111. camera.zoom = camera.zoom * 1.01f;
  112. }
  113. if (input.keyDown[KEY_PAGEDOWN])
  114. {
  115. Camera@ camera = cameraNode.GetComponent("Camera");
  116. camera.zoom = camera.zoom * 0.99f;
  117. }
  118. }
  119. void SubscribeToEvents()
  120. {
  121. // Subscribe HandleUpdate() function for processing update events
  122. SubscribeToEvent("Update", "HandleUpdate");
  123. // Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample
  124. UnsubscribeFromEvent("SceneUpdate");
  125. }
  126. void HandleUpdate(StringHash eventType, VariantMap& eventData)
  127. {
  128. // Take the frame time step, which is stored as a float
  129. float timeStep = eventData["TimeStep"].GetFloat();
  130. // Move the camera, scale movement with time step
  131. MoveCamera(timeStep);
  132. float halfWidth = graphics.width * 0.5f * PIXEL_SIZE;
  133. float halfHeight = graphics.height * 0.5f * PIXEL_SIZE;
  134. // Go through all sprites
  135. for (uint i = 0; i < spriteNodes.length; ++i)
  136. {
  137. Node@ spriteNode = spriteNodes[i];
  138. Vector3 moveSpeed = spriteNode.vars["MoveSpeed"].GetVector3();
  139. Vector3 newPosition = spriteNode.position + moveSpeed * timeStep;
  140. if (newPosition.x < -halfWidth || newPosition.x > halfWidth)
  141. {
  142. newPosition.x = spriteNode.position.x;
  143. moveSpeed.x = -moveSpeed.x;
  144. spriteNode.vars["MoveSpeed"] = moveSpeed;
  145. }
  146. if (newPosition.y < -halfHeight || newPosition.y > halfHeight)
  147. {
  148. newPosition.y = spriteNode.position.y;
  149. moveSpeed.y = -moveSpeed.y;
  150. spriteNode.vars["MoveSpeed"] = moveSpeed;
  151. }
  152. spriteNode.position = newPosition;
  153. spriteNode.Roll(spriteNode.vars["RotateSpeed"].GetFloat() * timeStep);
  154. }
  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>";