Urho2DIsometricDemo.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. //
  2. // Copyright (c) 2008-2020 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/Urho2D/AnimatedSprite2D.h>
  23. #include <Urho3D/Urho2D/AnimationSet2D.h>
  24. #include <Urho3D/UI/Button.h>
  25. #include <Urho3D/Graphics/Camera.h>
  26. #include <Urho3D/Urho2D/CollisionBox2D.h>
  27. #include <Urho3D/Urho2D/CollisionChain2D.h>
  28. #include <Urho3D/Urho2D/CollisionCircle2D.h>
  29. #include <Urho3D/Urho2D/CollisionPolygon2D.h>
  30. #include <Urho3D/Core/CoreEvents.h>
  31. #include <Urho3D/Graphics/DebugRenderer.h>
  32. #include <Urho3D/Engine/Engine.h>
  33. #include <Urho3D/UI/Font.h>
  34. #include <Urho3D/Graphics/Graphics.h>
  35. #include <Urho3D/Graphics/GraphicsEvents.h>
  36. #include <Urho3D/Input/Input.h>
  37. #include <Urho3D/Graphics/Octree.h>
  38. #include <Urho3D/Urho2D/PhysicsWorld2D.h>
  39. #include <Urho3D/Graphics/Renderer.h>
  40. #include <Urho3D/Resource/ResourceCache.h>
  41. #include <Urho3D/Urho2D/RigidBody2D.h>
  42. #include <Urho3D/Scene/Scene.h>
  43. #include <Urho3D/UI/Text.h>
  44. #include <Urho3D/Urho2D/TileMap2D.h>
  45. #include <Urho3D/Urho2D/TileMapLayer2D.h>
  46. #include <Urho3D/Urho2D/TmxFile2D.h>
  47. #include <Urho3D/UI/UIEvents.h>
  48. #include <Urho3D/Graphics/Zone.h>
  49. #include <Urho3D/Urho2D/PhysicsEvents2D.h>
  50. #include <Urho3D/DebugNew.h>
  51. #include "Character2D.h"
  52. #include "Utilities2D/Sample2D.h"
  53. #include "Utilities2D/Mover.h"
  54. #include "Urho2DIsometricDemo.h"
  55. Urho2DIsometricDemo::Urho2DIsometricDemo(Context* context) :
  56. Sample(context),
  57. zoom_(2.0f),
  58. drawDebug_(false)
  59. {
  60. // Register factory for the Character2D component so it can be created via CreateComponent
  61. Character2D::RegisterObject(context);
  62. // Register factory and attributes for the Mover component so it can be created via CreateComponent, and loaded / saved
  63. Mover::RegisterObject(context);
  64. }
  65. void Urho2DIsometricDemo::Setup()
  66. {
  67. Sample::Setup();
  68. engineParameters_[EP_SOUND] = true;
  69. }
  70. void Urho2DIsometricDemo::Start()
  71. {
  72. // Execute base class startup
  73. Sample::Start();
  74. sample2D_ = new Sample2D(context_);
  75. // Set filename for load/save functions
  76. sample2D_->demoFilename_ = "Isometric2D";
  77. // Create the scene content
  78. CreateScene();
  79. // Create the UI content
  80. sample2D_->CreateUIContent("ISOMETRIC 2.5D DEMO", character2D_->remainingLifes_, character2D_->remainingCoins_);
  81. auto* ui = GetSubsystem<UI>();
  82. Button* playButton = static_cast<Button*>(ui->GetRoot()->GetChild("PlayButton", true));
  83. SubscribeToEvent(playButton, E_RELEASED, URHO3D_HANDLER(Urho2DIsometricDemo, HandlePlayButton));
  84. // Hook up to the frame update events
  85. SubscribeToEvents();
  86. }
  87. void Urho2DIsometricDemo::CreateScene()
  88. {
  89. scene_ = new Scene(context_);
  90. sample2D_->scene_ = scene_;
  91. // Create the Octree, DebugRenderer and PhysicsWorld2D components to the scene
  92. scene_->CreateComponent<Octree>();
  93. scene_->CreateComponent<DebugRenderer>();
  94. auto* physicsWorld = scene_->CreateComponent<PhysicsWorld2D>();
  95. physicsWorld->SetGravity(Vector2(0.0f, 0.0f)); // Neutralize gravity as the character will always be grounded
  96. // Create camera
  97. cameraNode_ = scene_->CreateChild("Camera");
  98. auto* camera = cameraNode_->CreateComponent<Camera>();
  99. camera->SetOrthographic(true);
  100. auto* graphics = GetSubsystem<Graphics>();
  101. camera->SetOrthoSize((float)graphics->GetHeight() * PIXEL_SIZE);
  102. camera->SetZoom(2.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 (2.0) is set for full visibility at 1280x800 resolution)
  103. // Setup the viewport for displaying the scene
  104. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, camera));
  105. auto* renderer = GetSubsystem<Renderer>();
  106. renderer->SetViewport(0, viewport);
  107. auto* cache = GetSubsystem<ResourceCache>();
  108. // Create tile map from tmx file
  109. auto* tmxFile = cache->GetResource<TmxFile2D>("Urho2D/Tilesets/atrium.tmx");
  110. SharedPtr<Node> tileMapNode(scene_->CreateChild("TileMap"));
  111. auto* tileMap = tileMapNode->CreateComponent<TileMap2D>();
  112. tileMap->SetTmxFile(tmxFile);
  113. const TileMapInfo2D& info = tileMap->GetInfo();
  114. // Create Spriter Imp character (from sample 33_SpriterAnimation)
  115. Node* spriteNode = sample2D_->CreateCharacter(info, 0.0f, Vector3(-5.0f, 11.0f, 0.0f), 0.15f);
  116. character2D_ = spriteNode->CreateComponent<Character2D>(); // Create a logic component to handle character behavior
  117. // Scale character's speed on the Y axis according to tiles' aspect ratio
  118. character2D_->moveSpeedScale_ = info.tileHeight_ / info.tileWidth_;
  119. character2D_->zoom_ = camera->GetZoom();
  120. // Generate physics collision shapes from the tmx file's objects located in "Physics" (top) layer
  121. TileMapLayer2D* tileMapLayer = tileMap->GetLayer(tileMap->GetNumLayers() - 1);
  122. sample2D_->CreateCollisionShapesFromTMXObjects(tileMapNode, tileMapLayer, info);
  123. // Instantiate enemies at each placeholder of "MovingEntities" layer (placeholders are Poly Line objects defining a path from points)
  124. sample2D_->PopulateMovingEntities(tileMap->GetLayer(tileMap->GetNumLayers() - 2));
  125. // Instantiate coins to pick at each placeholder of "Coins" layer (placeholders for coins are Rectangle objects)
  126. TileMapLayer2D* coinsLayer = tileMap->GetLayer(tileMap->GetNumLayers() - 3);
  127. sample2D_->PopulateCoins(coinsLayer);
  128. // Init coins counters
  129. character2D_->remainingCoins_ = coinsLayer->GetNumObjects();
  130. character2D_->maxCoins_ = coinsLayer->GetNumObjects();
  131. // Check when scene is rendered
  132. SubscribeToEvent(E_ENDRENDERING, URHO3D_HANDLER(Urho2DIsometricDemo, HandleSceneRendered));
  133. }
  134. void Urho2DIsometricDemo::HandleCollisionBegin(StringHash eventType, VariantMap& eventData)
  135. {
  136. // Get colliding node
  137. auto* hitNode = static_cast<Node*>(eventData[PhysicsBeginContact2D::P_NODEA].GetPtr());
  138. if (hitNode->GetName() == "Imp")
  139. hitNode = static_cast<Node*>(eventData[PhysicsBeginContact2D::P_NODEB].GetPtr());
  140. String nodeName = hitNode->GetName();
  141. Node* character2DNode = scene_->GetChild("Imp", true);
  142. // Handle coins picking
  143. if (nodeName == "Coin")
  144. {
  145. hitNode->Remove();
  146. character2D_->remainingCoins_ -= 1;
  147. auto* ui = GetSubsystem<UI>();
  148. if (character2D_->remainingCoins_ == 0)
  149. {
  150. Text* instructions = static_cast<Text*>(ui->GetRoot()->GetChild("Instructions", true));
  151. instructions->SetText("!!! You have all the coins !!!");
  152. }
  153. Text* coinsText = static_cast<Text*>(ui->GetRoot()->GetChild("CoinsText", true));
  154. coinsText->SetText(String(character2D_->remainingCoins_)); // Update coins UI counter
  155. sample2D_->PlaySoundEffect("Powerup.wav");
  156. }
  157. // Handle interactions with enemies
  158. if (nodeName == "Orc")
  159. {
  160. auto* animatedSprite = character2DNode->GetComponent<AnimatedSprite2D>();
  161. float deltaX = character2DNode->GetPosition().x_ - hitNode->GetPosition().x_;
  162. // Orc killed if character is fighting in its direction when the contact occurs
  163. if (animatedSprite->GetAnimation() == "attack" && (deltaX < 0 == animatedSprite->GetFlipX()))
  164. {
  165. static_cast<Mover*>(hitNode->GetComponent<Mover>())->emitTime_ = 1;
  166. if (!hitNode->GetChild("Emitter", true))
  167. {
  168. hitNode->GetComponent("RigidBody2D")->Remove(); // Remove Orc's body
  169. sample2D_->SpawnEffect(hitNode);
  170. sample2D_->PlaySoundEffect("BigExplosion.wav");
  171. }
  172. }
  173. // Player killed if not fighting in the direction of the Orc when the contact occurs
  174. else
  175. {
  176. if (!character2DNode->GetChild("Emitter", true))
  177. {
  178. character2D_->wounded_ = true;
  179. if (nodeName == "Orc")
  180. {
  181. auto* orc = static_cast<Mover*>(hitNode->GetComponent<Mover>());
  182. orc->fightTimer_ = 1;
  183. }
  184. sample2D_->SpawnEffect(character2DNode);
  185. sample2D_->PlaySoundEffect("BigExplosion.wav");
  186. }
  187. }
  188. }
  189. }
  190. void Urho2DIsometricDemo::HandleSceneRendered(StringHash eventType, VariantMap& eventData)
  191. {
  192. UnsubscribeFromEvent(E_ENDRENDERING);
  193. // Save the scene so we can reload it later
  194. sample2D_->SaveScene(true);
  195. // Pause the scene as long as the UI is hiding it
  196. scene_->SetUpdateEnabled(false);
  197. }
  198. void Urho2DIsometricDemo::SubscribeToEvents()
  199. {
  200. // Subscribe HandleUpdate() function for processing update events
  201. SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(Urho2DIsometricDemo, HandleUpdate));
  202. // Subscribe HandlePostUpdate() function for processing post update events
  203. SubscribeToEvent(E_POSTUPDATE, URHO3D_HANDLER(Urho2DIsometricDemo, HandlePostUpdate));
  204. // Subscribe to PostRenderUpdate to draw debug geometry
  205. SubscribeToEvent(E_POSTRENDERUPDATE, URHO3D_HANDLER(Urho2DIsometricDemo, HandlePostRenderUpdate));
  206. // Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample
  207. UnsubscribeFromEvent(E_SCENEUPDATE);
  208. // Subscribe to Box2D contact listeners
  209. SubscribeToEvent(E_PHYSICSBEGINCONTACT2D, URHO3D_HANDLER(Urho2DIsometricDemo, HandleCollisionBegin));
  210. }
  211. void Urho2DIsometricDemo::HandleUpdate(StringHash eventType, VariantMap& eventData)
  212. {
  213. using namespace Update;
  214. // Zoom in/out
  215. if (cameraNode_)
  216. sample2D_->Zoom(cameraNode_->GetComponent<Camera>());
  217. auto* input = GetSubsystem<Input>();
  218. // Toggle debug geometry with 'Z' key
  219. if (input->GetKeyPress(KEY_Z))
  220. drawDebug_ = !drawDebug_;
  221. // Check for loading / saving the scene
  222. if (input->GetKeyPress(KEY_F5))
  223. sample2D_->SaveScene(false);
  224. if (input->GetKeyPress(KEY_F7))
  225. ReloadScene(false);
  226. }
  227. void Urho2DIsometricDemo::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  228. {
  229. if (!character2D_)
  230. return;
  231. Node* character2DNode = character2D_->GetNode();
  232. cameraNode_->SetPosition(Vector3(character2DNode->GetPosition().x_, character2DNode->GetPosition().y_, -10.0f)); // Camera tracks character
  233. }
  234. void Urho2DIsometricDemo::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  235. {
  236. if (drawDebug_)
  237. {
  238. auto* physicsWorld = scene_->GetComponent<PhysicsWorld2D>();
  239. physicsWorld->DrawDebugGeometry();
  240. Node* tileMapNode = scene_->GetChild("TileMap", true);
  241. auto* map = tileMapNode->GetComponent<TileMap2D>();
  242. map->DrawDebugGeometry(scene_->GetComponent<DebugRenderer>(), false);
  243. }
  244. }
  245. void Urho2DIsometricDemo::ReloadScene(bool reInit)
  246. {
  247. String filename = sample2D_->demoFilename_;
  248. if (!reInit)
  249. filename += "InGame";
  250. File loadFile(context_, GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Scenes/" + filename + ".xml", FILE_READ);
  251. scene_->LoadXML(loadFile);
  252. // After loading we have to reacquire the weak pointer to the Character2D component, as it has been recreated
  253. // Simply find the character's scene node by name as there's only one of them
  254. Node* character2DNode = scene_->GetChild("Imp", true);
  255. if (character2DNode)
  256. character2D_ = character2DNode->GetComponent<Character2D>();
  257. // Set what number to use depending whether reload is requested from 'PLAY' button (reInit=true) or 'F7' key (reInit=false)
  258. int lifes = character2D_->remainingLifes_;
  259. int coins = character2D_->remainingCoins_;
  260. if (reInit)
  261. {
  262. lifes = LIFES;
  263. coins = character2D_->maxCoins_;
  264. }
  265. // Update lifes UI
  266. auto* ui = GetSubsystem<UI>();
  267. Text* lifeText = static_cast<Text*>(ui->GetRoot()->GetChild("LifeText", true));
  268. lifeText->SetText(String(lifes));
  269. // Update coins UI
  270. Text* coinsText = static_cast<Text*>(ui->GetRoot()->GetChild("CoinsText", true));
  271. coinsText->SetText(String(coins));
  272. }
  273. void Urho2DIsometricDemo::HandlePlayButton(StringHash eventType, VariantMap& eventData)
  274. {
  275. // Remove fullscreen UI and unfreeze the scene
  276. auto* ui = GetSubsystem<UI>();
  277. if (static_cast<Text*>(ui->GetRoot()->GetChild("FullUI", true)))
  278. {
  279. ui->GetRoot()->GetChild("FullUI", true)->Remove();
  280. scene_->SetUpdateEnabled(true);
  281. }
  282. else
  283. // Reload scene
  284. ReloadScene(true);
  285. // Hide Instructions and Play/Exit buttons
  286. Text* instructionText = static_cast<Text*>(ui->GetRoot()->GetChild("Instructions", true));
  287. instructionText->SetText("");
  288. Button* exitButton = static_cast<Button*>(ui->GetRoot()->GetChild("ExitButton", true));
  289. exitButton->SetVisible(false);
  290. Button* playButton = static_cast<Button*>(ui->GetRoot()->GetChild("PlayButton", true));
  291. playButton->SetVisible(false);
  292. // Hide mouse cursor
  293. auto* input = GetSubsystem<Input>();
  294. input->SetMouseVisible(false);
  295. }
  296. URHO3D_DEFINE_APPLICATION_MAIN(Urho2DIsometricDemo)