Urho2DSprite.cpp 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. //
  2. // Copyright (c) 2008-2017 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include <Urho3D/Core/CoreEvents.h>
  23. #include <Urho3D/Engine/Engine.h>
  24. #include <Urho3D/Graphics/Camera.h>
  25. #include <Urho3D/Graphics/Graphics.h>
  26. #include <Urho3D/Graphics/Octree.h>
  27. #include <Urho3D/Graphics/Renderer.h>
  28. #include <Urho3D/Graphics/Zone.h>
  29. #include <Urho3D/Input/Input.h>
  30. #include <Urho3D/Resource/ResourceCache.h>
  31. #include <Urho3D/Scene/Scene.h>
  32. #include <Urho3D/UI/Font.h>
  33. #include <Urho3D/UI/Text.h>
  34. #include <Urho3D/Urho2D/AnimatedSprite2D.h>
  35. #include <Urho3D/Urho2D/AnimationSet2D.h>
  36. #include <Urho3D/Urho2D/Sprite2D.h>
  37. #include "Urho2DSprite.h"
  38. #include <Urho3D/DebugNew.h>
  39. // Number of static sprites to draw
  40. static const unsigned NUM_SPRITES = 200;
  41. static const StringHash VAR_MOVESPEED("MoveSpeed");
  42. static const StringHash VAR_ROTATESPEED("RotateSpeed");
  43. URHO3D_DEFINE_APPLICATION_MAIN(Urho2DSprite)
  44. Urho2DSprite::Urho2DSprite(Context* context) :
  45. Sample(context)
  46. {
  47. }
  48. void Urho2DSprite::Start()
  49. {
  50. // Execute base class startup
  51. Sample::Start();
  52. // Create the scene content
  53. CreateScene();
  54. // Create the UI content
  55. CreateInstructions();
  56. // Setup the viewport for displaying the scene
  57. SetupViewport();
  58. // Hook up to the frame update events
  59. SubscribeToEvents();
  60. // Set the mouse mode to use in the sample
  61. Sample::InitMouseMode(MM_FREE);
  62. }
  63. void Urho2DSprite::CreateScene()
  64. {
  65. scene_ = new Scene(context_);
  66. scene_->CreateComponent<Octree>();
  67. // Create camera node
  68. cameraNode_ = scene_->CreateChild("Camera");
  69. // Set camera's position
  70. cameraNode_->SetPosition(Vector3(0.0f, 0.0f, -10.0f));
  71. auto* camera = cameraNode_->CreateComponent<Camera>();
  72. camera->SetOrthographic(true);
  73. auto* graphics = GetSubsystem<Graphics>();
  74. camera->SetOrthoSize((float)graphics->GetHeight() * PIXEL_SIZE);
  75. auto* cache = GetSubsystem<ResourceCache>();
  76. // Get sprite
  77. auto* sprite = cache->GetResource<Sprite2D>("Urho2D/Aster.png");
  78. if (!sprite)
  79. return;
  80. float halfWidth = graphics->GetWidth() * 0.5f * PIXEL_SIZE;
  81. float halfHeight = graphics->GetHeight() * 0.5f * PIXEL_SIZE;
  82. for (unsigned i = 0; i < NUM_SPRITES; ++i)
  83. {
  84. SharedPtr<Node> spriteNode(scene_->CreateChild("StaticSprite2D"));
  85. spriteNode->SetPosition(Vector3(Random(-halfWidth, halfWidth), Random(-halfHeight, halfHeight), 0.0f));
  86. auto* staticSprite = spriteNode->CreateComponent<StaticSprite2D>();
  87. // Set random color
  88. staticSprite->SetColor(Color(Random(1.0f), Random(1.0f), Random(1.0f), 1.0f));
  89. // Set blend mode
  90. staticSprite->SetBlendMode(BLEND_ALPHA);
  91. // Set sprite
  92. staticSprite->SetSprite(sprite);
  93. // Set move speed
  94. spriteNode->SetVar(VAR_MOVESPEED, Vector3(Random(-2.0f, 2.0f), Random(-2.0f, 2.0f), 0.0f));
  95. // Set rotate speed
  96. spriteNode->SetVar(VAR_ROTATESPEED, Random(-90.0f, 90.0f));
  97. // Add to sprite node vector
  98. spriteNodes_.Push(spriteNode);
  99. }
  100. // Get animation set
  101. auto* animationSet = cache->GetResource<AnimationSet2D>("Urho2D/GoldIcon.scml");
  102. if (!animationSet)
  103. return;
  104. SharedPtr<Node> spriteNode(scene_->CreateChild("AnimatedSprite2D"));
  105. spriteNode->SetPosition(Vector3(0.0f, 0.0f, -1.0f));
  106. auto* animatedSprite = spriteNode->CreateComponent<AnimatedSprite2D>();
  107. // Set animation
  108. animatedSprite->SetAnimationSet(animationSet);
  109. animatedSprite->SetAnimation("idle");
  110. }
  111. void Urho2DSprite::CreateInstructions()
  112. {
  113. auto* cache = GetSubsystem<ResourceCache>();
  114. auto* ui = GetSubsystem<UI>();
  115. // Construct new Text object, set string to display and font to use
  116. auto* instructionText = ui->GetRoot()->CreateChild<Text>();
  117. instructionText->SetText("Use WASD keys to move, use PageUp PageDown keys to zoom.");
  118. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  119. // Position the text relative to the screen center
  120. instructionText->SetHorizontalAlignment(HA_CENTER);
  121. instructionText->SetVerticalAlignment(VA_CENTER);
  122. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  123. }
  124. void Urho2DSprite::SetupViewport()
  125. {
  126. auto* renderer = GetSubsystem<Renderer>();
  127. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  128. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  129. renderer->SetViewport(0, viewport);
  130. }
  131. void Urho2DSprite::MoveCamera(float timeStep)
  132. {
  133. // Do not move if the UI has a focused element (the console)
  134. if (GetSubsystem<UI>()->GetFocusElement())
  135. return;
  136. auto* input = GetSubsystem<Input>();
  137. // Movement speed as world units per second
  138. const float MOVE_SPEED = 4.0f;
  139. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  140. if (input->GetKeyDown(KEY_W))
  141. cameraNode_->Translate(Vector3::UP * MOVE_SPEED * timeStep);
  142. if (input->GetKeyDown(KEY_S))
  143. cameraNode_->Translate(Vector3::DOWN * MOVE_SPEED * timeStep);
  144. if (input->GetKeyDown(KEY_A))
  145. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  146. if (input->GetKeyDown(KEY_D))
  147. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  148. if (input->GetKeyDown(KEY_PAGEUP))
  149. {
  150. auto* camera = cameraNode_->GetComponent<Camera>();
  151. camera->SetZoom(camera->GetZoom() * 1.01f);
  152. }
  153. if (input->GetKeyDown(KEY_PAGEDOWN))
  154. {
  155. auto* camera = cameraNode_->GetComponent<Camera>();
  156. camera->SetZoom(camera->GetZoom() * 0.99f);
  157. }
  158. }
  159. void Urho2DSprite::SubscribeToEvents()
  160. {
  161. // Subscribe HandleUpdate() function for processing update events
  162. SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(Urho2DSprite, HandleUpdate));
  163. // Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample
  164. UnsubscribeFromEvent(E_SCENEUPDATE);
  165. }
  166. void Urho2DSprite::HandleUpdate(StringHash eventType, VariantMap& eventData)
  167. {
  168. using namespace Update;
  169. // Take the frame time step, which is stored as a float
  170. float timeStep = eventData[P_TIMESTEP].GetFloat();
  171. // Move the camera, scale movement with time step
  172. MoveCamera(timeStep);
  173. auto* graphics = GetSubsystem<Graphics>();
  174. float halfWidth = (float)graphics->GetWidth() * 0.5f * PIXEL_SIZE;
  175. float halfHeight = (float)graphics->GetHeight() * 0.5f * PIXEL_SIZE;
  176. for (unsigned i = 0; i < spriteNodes_.Size(); ++i)
  177. {
  178. SharedPtr<Node> node = spriteNodes_[i];
  179. Vector3 position = node->GetPosition();
  180. Vector3 moveSpeed = node->GetVar(VAR_MOVESPEED).GetVector3();
  181. Vector3 newPosition = position + moveSpeed * timeStep;
  182. if (newPosition.x_ < -halfWidth || newPosition.x_ > halfWidth)
  183. {
  184. newPosition.x_ = position.x_;
  185. moveSpeed.x_ = -moveSpeed.x_;
  186. node->SetVar(VAR_MOVESPEED, moveSpeed);
  187. }
  188. if (newPosition.y_ < -halfHeight || newPosition.y_ > halfHeight)
  189. {
  190. newPosition.y_ = position.y_;
  191. moveSpeed.y_ = -moveSpeed.y_;
  192. node->SetVar(VAR_MOVESPEED, moveSpeed);
  193. }
  194. node->SetPosition(newPosition);
  195. float rotateSpeed = node->GetVar(VAR_ROTATESPEED).GetFloat();
  196. node->Roll(rotateSpeed * timeStep);
  197. }
  198. }