36_Urho2DTileMap.as 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. // Urho2D tile map example.
  2. // This sample demonstrates:
  3. // - Creating a 2D scene with tile map
  4. // - Displaying the scene using the Renderer subsystem
  5. // - Handling keyboard to move and zoom 2D camera
  6. // - Interacting with the tile map
  7. #include "Scripts/Utilities/Sample.as"
  8. void Start()
  9. {
  10. // Execute the common startup for samples
  11. SampleStart();
  12. // Enable OS cursor
  13. input.mouseVisible = true;
  14. // Create the scene content
  15. CreateScene();
  16. // Create the UI content
  17. CreateInstructions();
  18. // Setup the viewport for displaying the scene
  19. SetupViewport();
  20. // Set the mouse mode to use in the sample
  21. SampleInitMouseMode(MM_RELATIVE);
  22. // Hook up to the frame update events
  23. SubscribeToEvents();
  24. }
  25. void CreateScene()
  26. {
  27. scene_ = Scene();
  28. // Create the Octree component to the scene. This is required before adding any drawable components, or else nothing will
  29. // show up. The default octree volume will be from (-1000, -1000, -1000) to (1000, 1000, 1000) in world coordinates; it
  30. // is also legal to place objects outside the volume but their visibility can then not be checked in a hierarchically
  31. // optimizing manner
  32. scene_.CreateComponent("Octree");
  33. // Create a scene node for the camera, which we will move around
  34. // The camera will use default settings (1000 far clip distance, 45 degrees FOV, set aspect ratio automatically)
  35. cameraNode = scene_.CreateChild("Camera");
  36. // Set an initial position for the camera scene node above the plane
  37. cameraNode.position = Vector3(0.0f, 0.0f, -10.0f);
  38. Camera@ camera = cameraNode.CreateComponent("Camera");
  39. camera.orthographic = true;
  40. camera.orthoSize = graphics.height * PIXEL_SIZE;
  41. camera.zoom = 1.0f * Min(graphics.width / 1280.0f, graphics.height / 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)
  42. // Get tmx file
  43. TmxFile2D@ tmxFile = cache.GetResource("TmxFile2D", "Urho2D/isometric_grass_and_water.tmx");
  44. if (tmxFile is null)
  45. return;
  46. Node@ tileMapNode = scene_.CreateChild("TileMap");
  47. tileMapNode.position = Vector3(0.0f, 0.0f, -1.0f);
  48. TileMap2D@ tileMap = tileMapNode.CreateComponent("TileMap2D");
  49. tileMap.tmxFile = tmxFile;
  50. // Set camera's position;
  51. TileMapInfo2D@ info = tileMap.info;
  52. float x = info.mapWidth * 0.5f;
  53. float y = info.mapHeight * 0.5f;
  54. cameraNode.position = Vector3(x, y, -10.0f);
  55. }
  56. void CreateInstructions()
  57. {
  58. // Construct new Text object, set string to display and font to use
  59. Text@ instructionText = ui.root.CreateChild("Text");
  60. instructionText.text = "Use WASD keys and mouse to move, Use PageUp PageDown to zoom.\n LMB to remove a tile, RMB to swap grass and water.";
  61. instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15);
  62. // Position the text relative to the screen center
  63. instructionText.horizontalAlignment = HA_CENTER;
  64. instructionText.verticalAlignment = VA_CENTER;
  65. instructionText.SetPosition(0, ui.root.height / 4);
  66. }
  67. void SetupViewport()
  68. {
  69. // 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
  70. // at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward / deferred) to
  71. // use, but now we just use full screen and default render path configured in the engine command line options
  72. Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera"));
  73. renderer.viewports[0] = viewport;
  74. }
  75. void MoveCamera(float timeStep)
  76. {
  77. // Do not move if the UI has a focused element (the console)
  78. if (ui.focusElement !is null)
  79. return;
  80. // Movement speed as world units per second
  81. const float MOVE_SPEED = 4.0f;
  82. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  83. if (input.keyDown[KEY_W])
  84. cameraNode.Translate(Vector3::UP * MOVE_SPEED * timeStep);
  85. if (input.keyDown[KEY_S])
  86. cameraNode.Translate(Vector3::DOWN * MOVE_SPEED * timeStep);
  87. if (input.keyDown[KEY_A])
  88. cameraNode.Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  89. if (input.keyDown[KEY_D])
  90. cameraNode.Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  91. if (input.keyDown[KEY_PAGEUP])
  92. {
  93. Camera@ camera = cameraNode.GetComponent("Camera");
  94. camera.zoom = camera.zoom * 1.01f;
  95. }
  96. if (input.keyDown[KEY_PAGEDOWN])
  97. {
  98. Camera@ camera = cameraNode.GetComponent("Camera");
  99. camera.zoom = camera.zoom * 0.99f;
  100. }
  101. }
  102. void SubscribeToEvents()
  103. {
  104. // Subscribe HandleUpdate() function for processing update events
  105. SubscribeToEvent("Update", "HandleUpdate");
  106. // Listen to mouse clicks
  107. SubscribeToEvent("MouseButtonDown", "HandleMouseButtonDown");
  108. // Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample
  109. UnsubscribeFromEvent("SceneUpdate");
  110. }
  111. void HandleUpdate(StringHash eventType, VariantMap& eventData)
  112. {
  113. // Take the frame time step, which is stored as a float
  114. float timeStep = eventData["TimeStep"].GetFloat();
  115. // Move the camera, scale movement with time step
  116. MoveCamera(timeStep);
  117. }
  118. void HandleMouseButtonDown(StringHash eventType, VariantMap& eventData)
  119. {
  120. Node@ tileMapNode = scene_.GetChild("TileMap", true);
  121. TileMap2D@ map = tileMapNode.GetComponent("TileMap2D");
  122. TileMapLayer2D@ layer = map.GetLayer(0);
  123. Vector2 pos = GetMousePositionXY();
  124. int x, y;
  125. if (map.PositionToTileIndex(x, y, pos))
  126. {
  127. // Get tile's sprite. Note that layer.GetTile(x, y).sprite is read-only, so we get the sprite through tile's node
  128. Node@ n = layer.GetTileNode(x, y);
  129. if (n is null)
  130. return;
  131. StaticSprite2D@ sprite = n.GetComponent("StaticSprite2D");
  132. if (input.mouseButtonDown[MOUSEB_RIGHT])
  133. {
  134. // Swap grass and water
  135. if (layer.GetTile(x, y).gid < 9) // First 8 sprites in the "isometric_grass_and_water.png" tileset are mostly grass and from 9 to 24 they are mostly water
  136. sprite.sprite = layer.GetTile(0, 0).sprite; // Replace grass by water sprite used in top tile
  137. else sprite.sprite = layer.GetTile(24, 24).sprite; // Replace water by grass sprite used in bottom tile
  138. }
  139. else sprite.sprite = null; // 'Remove' sprite
  140. }
  141. }
  142. Vector2 GetMousePositionXY()
  143. {
  144. Camera@ camera = cameraNode.GetComponent("Camera");
  145. Vector3 screenPoint = Vector3(float(input.mousePosition.x) / graphics.width, float(input.mousePosition.y) / graphics.height, 10.0f);
  146. Vector3 worldPoint = camera.ScreenToWorldPoint(screenPoint);
  147. return Vector2(worldPoint.x, worldPoint.y);
  148. }
  149. // Create XML patch instructions for screen joystick layout specific to this sample app
  150. String patchInstructions =
  151. "<patch>" +
  152. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" +
  153. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Zoom In</replace>" +
  154. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" +
  155. " <element type=\"Text\">" +
  156. " <attribute name=\"Name\" value=\"KeyBinding\" />" +
  157. " <attribute name=\"Text\" value=\"PAGEUP\" />" +
  158. " </element>" +
  159. " </add>" +
  160. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" +
  161. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Zoom Out</replace>" +
  162. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" +
  163. " <element type=\"Text\">" +
  164. " <attribute name=\"Name\" value=\"KeyBinding\" />" +
  165. " <attribute name=\"Text\" value=\"PAGEDOWN\" />" +
  166. " </element>" +
  167. " </add>" +
  168. "</patch>";