Urho2DIsometricDemo.cpp 13 KB

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