Urho2DTileMap.cpp 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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/Graphics/Camera.h>
  24. #include <Urho3D/Engine/Engine.h>
  25. #include <Urho3D/UI/Font.h>
  26. #include <Urho3D/Graphics/Graphics.h>
  27. #include <Urho3D/Input/Input.h>
  28. #include <Urho3D/Graphics/Octree.h>
  29. #include <Urho3D/Graphics/Renderer.h>
  30. #include <Urho3D/Resource/ResourceCache.h>
  31. #include <Urho3D/Scene/Scene.h>
  32. #include <Urho3D/Urho2D/StaticSprite2D.h>
  33. #include <Urho3D/UI/Text.h>
  34. #include <Urho3D/Urho2D/TileMap2D.h>
  35. #include <Urho3D/Urho2D/TileMapLayer2D.h>
  36. #include <Urho3D/Urho2D/TmxFile2D.h>
  37. #include "Urho2DTileMap.h"
  38. #include <Urho3D/DebugNew.h>
  39. URHO3D_DEFINE_APPLICATION_MAIN(Urho2DTileMap)
  40. Urho2DTileMap::Urho2DTileMap(Context* context) :
  41. Sample(context)
  42. {
  43. }
  44. void Urho2DTileMap::Start()
  45. {
  46. // Execute base class startup
  47. Sample::Start();
  48. // Enable OS cursor
  49. GetSubsystem<Input>()->SetMouseVisible(true);
  50. // Create the scene content
  51. CreateScene();
  52. // Create the UI content
  53. CreateInstructions();
  54. // Setup the viewport for displaying the scene
  55. SetupViewport();
  56. // Hook up to the frame update events
  57. SubscribeToEvents();
  58. // Set the mouse mode to use in the sample
  59. Sample::InitMouseMode(MM_RELATIVE);
  60. }
  61. void Urho2DTileMap::CreateScene()
  62. {
  63. scene_ = new Scene(context_);
  64. scene_->CreateComponent<Octree>();
  65. // Create camera node
  66. cameraNode_ = scene_->CreateChild("Camera");
  67. // Set camera's position
  68. cameraNode_->SetPosition(Vector3(0.0f, 0.0f, -10.0f));
  69. Camera* camera = cameraNode_->CreateComponent<Camera>();
  70. camera->SetOrthographic(true);
  71. Graphics* graphics = GetSubsystem<Graphics>();
  72. camera->SetOrthoSize((float)graphics->GetHeight() * PIXEL_SIZE);
  73. camera->SetZoom(1.0f * Min((float)graphics->GetWidth() / 1280.0f, (float)graphics->GetHeight() / 800.0f)); // Set zoom according to user's resolution to ensure full visibility (initial zoom (1.0) is set for full visibility at 1280x800 resolution)
  74. ResourceCache* cache = GetSubsystem<ResourceCache>();
  75. // Get tmx file
  76. TmxFile2D* tmxFile = cache->GetResource<TmxFile2D>("Urho2D/isometric_grass_and_water.tmx");
  77. if (!tmxFile)
  78. return;
  79. SharedPtr<Node> tileMapNode(scene_->CreateChild("TileMap"));
  80. tileMapNode->SetPosition(Vector3(0.0f, 0.0f, -1.0f));
  81. TileMap2D* tileMap = tileMapNode->CreateComponent<TileMap2D>();
  82. // Set animation
  83. tileMap->SetTmxFile(tmxFile);
  84. // Set camera's position
  85. const TileMapInfo2D& info = tileMap->GetInfo();
  86. float x = info.GetMapWidth() * 0.5f;
  87. float y = info.GetMapHeight() * 0.5f;
  88. cameraNode_->SetPosition(Vector3(x, y, -10.0f));
  89. }
  90. void Urho2DTileMap::CreateInstructions()
  91. {
  92. ResourceCache* cache = GetSubsystem<ResourceCache>();
  93. UI* ui = GetSubsystem<UI>();
  94. // Construct new Text object, set string to display and font to use
  95. Text* instructionText = ui->GetRoot()->CreateChild<Text>();
  96. instructionText->SetText("Use WASD keys to move, use PageUp PageDown keys to zoom.\n LMB to remove a tile, RMB to swap grass and water.");
  97. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  98. // Position the text relative to the screen center
  99. instructionText->SetHorizontalAlignment(HA_CENTER);
  100. instructionText->SetVerticalAlignment(VA_CENTER);
  101. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  102. }
  103. void Urho2DTileMap::SetupViewport()
  104. {
  105. Renderer* renderer = GetSubsystem<Renderer>();
  106. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  107. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  108. renderer->SetViewport(0, viewport);
  109. }
  110. void Urho2DTileMap::MoveCamera(float timeStep)
  111. {
  112. // Do not move if the UI has a focused element (the console)
  113. if (GetSubsystem<UI>()->GetFocusElement())
  114. return;
  115. Input* input = GetSubsystem<Input>();
  116. // Movement speed as world units per second
  117. const float MOVE_SPEED = 4.0f;
  118. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  119. if (input->GetKeyDown(KEY_W))
  120. cameraNode_->Translate(Vector3::UP * MOVE_SPEED * timeStep);
  121. if (input->GetKeyDown(KEY_S))
  122. cameraNode_->Translate(Vector3::DOWN * MOVE_SPEED * timeStep);
  123. if (input->GetKeyDown(KEY_A))
  124. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  125. if (input->GetKeyDown(KEY_D))
  126. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  127. if (input->GetKeyDown(KEY_PAGEUP))
  128. {
  129. Camera* camera = cameraNode_->GetComponent<Camera>();
  130. camera->SetZoom(camera->GetZoom() * 1.01f);
  131. }
  132. if (input->GetKeyDown(KEY_PAGEDOWN))
  133. {
  134. Camera* camera = cameraNode_->GetComponent<Camera>();
  135. camera->SetZoom(camera->GetZoom() * 0.99f);
  136. }
  137. }
  138. void Urho2DTileMap::SubscribeToEvents()
  139. {
  140. // Subscribe HandleUpdate() function for processing update events
  141. SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(Urho2DTileMap, HandleUpdate));
  142. // Listen to mouse clicks
  143. SubscribeToEvent(E_MOUSEBUTTONDOWN, URHO3D_HANDLER(Urho2DTileMap, HandleMouseButtonDown));
  144. // Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample
  145. UnsubscribeFromEvent(E_SCENEUPDATE);
  146. }
  147. void Urho2DTileMap::HandleUpdate(StringHash eventType, VariantMap& eventData)
  148. {
  149. using namespace Update;
  150. // Take the frame time step, which is stored as a float
  151. float timeStep = eventData[P_TIMESTEP].GetFloat();
  152. // Move the camera, scale movement with time step
  153. MoveCamera(timeStep);
  154. }
  155. void Urho2DTileMap::HandleMouseButtonDown(StringHash eventType, VariantMap& eventData)
  156. {
  157. Input* input = GetSubsystem<Input>();
  158. Node* tileMapNode = scene_->GetChild("TileMap", true);
  159. TileMap2D* map = tileMapNode->GetComponent<TileMap2D>();
  160. TileMapLayer2D* layer = map->GetLayer(0);
  161. Vector2 pos = GetMousePositionXY();
  162. int x, y;
  163. if (map->PositionToTileIndex(x, y, pos))
  164. {
  165. // Get tile's sprite. Note that layer.GetTile(x, y).sprite is read-only, so we get the sprite through tile's node
  166. Node* n = layer->GetTileNode(x, y);
  167. if (!n)
  168. return;
  169. StaticSprite2D* sprite = n->GetComponent<StaticSprite2D>();
  170. if (input->GetMouseButtonDown(MOUSEB_RIGHT))
  171. {
  172. // Swap grass and water
  173. if (layer->GetTile(x, y)->GetGid() < 9) // First 8 sprites in the "isometric_grass_and_water.png" tileset are mostly grass and from 9 to 24 they are mostly water
  174. sprite->SetSprite(layer->GetTile(0, 0)->GetSprite()); // Replace grass by water sprite used in top tile
  175. else sprite->SetSprite(layer->GetTile(24, 24)->GetSprite()); // Replace water by grass sprite used in bottom tile
  176. }
  177. else sprite->SetSprite(NULL); // 'Remove' sprite
  178. }
  179. }
  180. Vector2 Urho2DTileMap::GetMousePositionXY()
  181. {
  182. Input* input = GetSubsystem<Input>();
  183. Graphics* graphics = GetSubsystem<Graphics>();
  184. Camera* camera = cameraNode_->GetComponent<Camera>();
  185. Vector3 screenPoint = Vector3((float)input->GetMousePosition().x_ / graphics->GetWidth(), (float)input->GetMousePosition().y_ / graphics->GetHeight(), 10.0f);
  186. Vector3 worldPoint = camera->ScreenToWorldPoint(screenPoint);
  187. return Vector2(worldPoint.x_, worldPoint.y_);
  188. }