Urho2DIsometricDemo.cpp 14 KB

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