Urho2DSprite.cpp 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. //
  2. // Copyright (c) 2008-2015 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/Urho3D.h>
  23. #include <Urho3D/Urho2D/AnimatedSprite2D.h>
  24. #include <Urho3D/Urho2D/AnimationSet2D.h>
  25. #include <Urho3D/Graphics/Camera.h>
  26. #include <Urho3D/Core/CoreEvents.h>
  27. #include <Urho3D/Engine/Engine.h>
  28. #include <Urho3D/UI/Font.h>
  29. #include <Urho3D/Graphics/Graphics.h>
  30. #include <Urho3D/Input/Input.h>
  31. #include <Urho3D/Graphics/Octree.h>
  32. #include <Urho3D/Graphics/Renderer.h>
  33. #include <Urho3D/Resource/ResourceCache.h>
  34. #include <Urho3D/Scene/Scene.h>
  35. #include <Urho3D/Urho2D/Sprite2D.h>
  36. #include <Urho3D/Urho2D/StaticSprite2D.h>
  37. #include <Urho3D/UI/Text.h>
  38. #include <Urho3D/Graphics/Zone.h>
  39. #include "Urho2DSprite.h"
  40. #include <Urho3D/DebugNew.h>
  41. // Number of static sprites to draw
  42. static const unsigned NUM_SPRITES = 200;
  43. static const StringHash VAR_MOVESPEED("MoveSpeed");
  44. static const StringHash VAR_ROTATESPEED("RotateSpeed");
  45. DEFINE_APPLICATION_MAIN(Urho2DSprite)
  46. Urho2DSprite::Urho2DSprite(Context* context) :
  47. Sample(context)
  48. {
  49. }
  50. void Urho2DSprite::Start()
  51. {
  52. // Execute base class startup
  53. Sample::Start();
  54. // Create the scene content
  55. CreateScene();
  56. // Create the UI content
  57. CreateInstructions();
  58. // Setup the viewport for displaying the scene
  59. SetupViewport();
  60. // Hook up to the frame update events
  61. SubscribeToEvents();
  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. Camera* camera = cameraNode_->CreateComponent<Camera>();
  72. camera->SetOrthographic(true);
  73. Graphics* graphics = GetSubsystem<Graphics>();
  74. camera->SetOrthoSize((float)graphics->GetHeight() * PIXEL_SIZE);
  75. ResourceCache* cache = GetSubsystem<ResourceCache>();
  76. // Get sprite
  77. Sprite2D* 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. StaticSprite2D* 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. AnimationSet2D* 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. AnimatedSprite2D* animatedSprite = spriteNode->CreateComponent<AnimatedSprite2D>();
  107. // Set animation
  108. animatedSprite->SetAnimation(animationSet, "idle");
  109. }
  110. void Urho2DSprite::CreateInstructions()
  111. {
  112. ResourceCache* cache = GetSubsystem<ResourceCache>();
  113. UI* ui = GetSubsystem<UI>();
  114. // Construct new Text object, set string to display and font to use
  115. Text* instructionText = ui->GetRoot()->CreateChild<Text>();
  116. instructionText->SetText("Use WASD keys to move, use PageUp PageDown keys to zoom.");
  117. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  118. // Position the text relative to the screen center
  119. instructionText->SetHorizontalAlignment(HA_CENTER);
  120. instructionText->SetVerticalAlignment(VA_CENTER);
  121. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  122. }
  123. void Urho2DSprite::SetupViewport()
  124. {
  125. Renderer* renderer = GetSubsystem<Renderer>();
  126. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  127. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  128. renderer->SetViewport(0, viewport);
  129. }
  130. void Urho2DSprite::MoveCamera(float timeStep)
  131. {
  132. // Do not move if the UI has a focused element (the console)
  133. if (GetSubsystem<UI>()->GetFocusElement())
  134. return;
  135. Input* input = GetSubsystem<Input>();
  136. // Movement speed as world units per second
  137. const float MOVE_SPEED = 4.0f;
  138. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  139. if (input->GetKeyDown('W'))
  140. cameraNode_->Translate(Vector3::UP * MOVE_SPEED * timeStep);
  141. if (input->GetKeyDown('S'))
  142. cameraNode_->Translate(Vector3::DOWN * MOVE_SPEED * timeStep);
  143. if (input->GetKeyDown('A'))
  144. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  145. if (input->GetKeyDown('D'))
  146. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  147. if (input->GetKeyDown(KEY_PAGEUP))
  148. {
  149. Camera* camera = cameraNode_->GetComponent<Camera>();
  150. camera->SetZoom(camera->GetZoom() * 1.01f);
  151. }
  152. if (input->GetKeyDown(KEY_PAGEDOWN))
  153. {
  154. Camera* camera = cameraNode_->GetComponent<Camera>();
  155. camera->SetZoom(camera->GetZoom() * 0.99f);
  156. }
  157. }
  158. void Urho2DSprite::SubscribeToEvents()
  159. {
  160. // Subscribe HandleUpdate() function for processing update events
  161. SubscribeToEvent(E_UPDATE, HANDLER(Urho2DSprite, HandleUpdate));
  162. // Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample
  163. UnsubscribeFromEvent(E_SCENEUPDATE);
  164. }
  165. void Urho2DSprite::HandleUpdate(StringHash eventType, VariantMap& eventData)
  166. {
  167. using namespace Update;
  168. // Take the frame time step, which is stored as a float
  169. float timeStep = eventData[P_TIMESTEP].GetFloat();
  170. // Move the camera, scale movement with time step
  171. MoveCamera(timeStep);
  172. Graphics* graphics = GetSubsystem<Graphics>();
  173. float halfWidth = (float)graphics->GetWidth() * 0.5f * PIXEL_SIZE;
  174. float halfHeight = (float)graphics->GetHeight() * 0.5f * PIXEL_SIZE;
  175. for (unsigned i = 0; i < spriteNodes_.Size(); ++i)
  176. {
  177. SharedPtr<Node> node = spriteNodes_[i];
  178. Vector3 position = node->GetPosition();
  179. Vector3 moveSpeed = node->GetVar(VAR_MOVESPEED).GetVector3();
  180. Vector3 newPosition = position + moveSpeed * timeStep;
  181. if (newPosition.x_ < -halfWidth || newPosition.x_ > halfWidth)
  182. {
  183. newPosition.x_ = position.x_;
  184. moveSpeed.x_ = -moveSpeed.x_;
  185. node->SetVar(VAR_MOVESPEED, moveSpeed);
  186. }
  187. if (newPosition.y_ < -halfHeight || newPosition.y_ > halfHeight)
  188. {
  189. newPosition.y_ = position.y_;
  190. moveSpeed.y_ = -moveSpeed.y_;
  191. node->SetVar(VAR_MOVESPEED, moveSpeed);
  192. }
  193. node->SetPosition(newPosition);
  194. float rotateSpeed = node->GetVar(VAR_ROTATESPEED).GetFloat();
  195. node->Roll(rotateSpeed * timeStep);
  196. }
  197. }