Sample2D.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. //
  2. // Copyright (c) 2008-2022 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/Audio/Sound.h>
  23. #include <Urho3D/Audio/SoundSource.h>
  24. #include <Urho3D/Core/Context.h>
  25. #include <Urho3D/Core/CoreEvents.h>
  26. #include <Urho3D/Core/StringUtils.h>
  27. #include <Urho3D/Engine/Engine.h>
  28. #include <Urho3D/Graphics/Camera.h>
  29. #include <Urho3D/GraphicsAPI/Texture2D.h>
  30. #include <Urho3D/Input/Input.h>
  31. #include <Urho3D/IO/File.h>
  32. #include <Urho3D/IO/FileSystem.h>
  33. #include <Urho3D/Physics2D/CollisionBox2D.h>
  34. #include <Urho3D/Physics2D/CollisionChain2D.h>
  35. #include <Urho3D/Physics2D/CollisionCircle2D.h>
  36. #include <Urho3D/Physics2D/CollisionEdge2D.h>
  37. #include <Urho3D/Physics2D/CollisionPolygon2D.h>
  38. #include <Urho3D/Physics2D/RigidBody2D.h>
  39. #include <Urho3D/Resource/ResourceCache.h>
  40. #include <Urho3D/Scene/Scene.h>
  41. #include <Urho3D/Scene/ValueAnimation.h>
  42. #include <Urho3D/UI/BorderImage.h>
  43. #include <Urho3D/UI/Button.h>
  44. #include <Urho3D/UI/Font.h>
  45. #include <Urho3D/UI/Text.h>
  46. #include <Urho3D/UI/UI.h>
  47. #include <Urho3D/UI/UIEvents.h>
  48. #include <Urho3D/UI/Window.h>
  49. #include <Urho3D/Urho2D/AnimatedSprite2D.h>
  50. #include <Urho3D/Urho2D/AnimationSet2D.h>
  51. #include <Urho3D/Urho2D/ParticleEffect2D.h>
  52. #include <Urho3D/Urho2D/ParticleEmitter2D.h>
  53. #include <Urho3D/Urho2D/TileMap2D.h>
  54. #include <Urho3D/Urho2D/TileMapLayer2D.h>
  55. #include <Urho3D/Urho2D/TmxFile2D.h>
  56. #include "Utilities2D/Mover.h"
  57. #include "Sample2D.h"
  58. Sample2D::Sample2D(Context* context) :
  59. Object(context)
  60. {
  61. }
  62. void Sample2D::CreateCollisionShapesFromTMXObjects(Node* tileMapNode, TileMapLayer2D* tileMapLayer, const TileMapInfo2D& info)
  63. {
  64. // Create rigid body to the root node
  65. auto* body = tileMapNode->CreateComponent<RigidBody2D>();
  66. body->SetBodyType(BT_STATIC);
  67. // Generate physics collision shapes and rigid bodies from the tmx file's objects located in "Physics" layer
  68. for (unsigned i = 0; i < tileMapLayer->GetNumObjects(); ++i)
  69. {
  70. TileMapObject2D* tileMapObject = tileMapLayer->GetObject(i); // Get physics objects
  71. // Create collision shape from tmx object
  72. switch (tileMapObject->GetObjectType())
  73. {
  74. case OT_RECTANGLE:
  75. {
  76. CreateRectangleShape(tileMapNode, tileMapObject, tileMapObject->GetSize(), info);
  77. }
  78. break;
  79. case OT_ELLIPSE:
  80. {
  81. CreateCircleShape(tileMapNode, tileMapObject, tileMapObject->GetSize().x_ / 2, info); // Ellipse is built as a Circle shape as it doesn't exist in Box2D
  82. }
  83. break;
  84. case OT_POLYGON:
  85. {
  86. CreatePolygonShape(tileMapNode, tileMapObject);
  87. }
  88. break;
  89. case OT_POLYLINE:
  90. {
  91. CreatePolyLineShape(tileMapNode, tileMapObject);
  92. }
  93. break;
  94. }
  95. }
  96. }
  97. CollisionBox2D* Sample2D::CreateRectangleShape(Node* node, TileMapObject2D* object, const Vector2& size, const TileMapInfo2D& info)
  98. {
  99. auto* shape = node->CreateComponent<CollisionBox2D>();
  100. shape->SetSize(size);
  101. if (info.orientation_ == O_ORTHOGONAL)
  102. shape->SetCenter(object->GetPosition() + size / 2);
  103. else
  104. {
  105. shape->SetCenter(object->GetPosition() + Vector2(info.tileWidth_ / 2, 0.0f));
  106. shape->SetAngle(45.0f); // If our tile map is isometric then shape is losange
  107. }
  108. shape->SetFriction(0.8f);
  109. if (object->HasProperty("Friction"))
  110. shape->SetFriction(ToFloat(object->GetProperty("Friction")));
  111. return shape;
  112. }
  113. CollisionCircle2D* Sample2D::CreateCircleShape(Node* node, TileMapObject2D* object, float radius, const TileMapInfo2D& info)
  114. {
  115. auto* shape = node->CreateComponent<CollisionCircle2D>();
  116. Vector2 size = object->GetSize();
  117. if (info.orientation_ == O_ORTHOGONAL)
  118. shape->SetCenter(object->GetPosition() + size / 2);
  119. else
  120. {
  121. shape->SetCenter(object->GetPosition() + Vector2(info.tileWidth_ / 2, 0.0f));
  122. }
  123. shape->SetRadius(radius);
  124. shape->SetFriction(0.8f);
  125. if (object->HasProperty("Friction"))
  126. shape->SetFriction(ToFloat(object->GetProperty("Friction")));
  127. return shape;
  128. }
  129. CollisionPolygon2D* Sample2D::CreatePolygonShape(Node* node, TileMapObject2D* object)
  130. {
  131. auto* shape = node->CreateComponent<CollisionPolygon2D>();
  132. int numVertices = object->GetNumPoints();
  133. shape->SetVertexCount(numVertices);
  134. for (int i = 0; i < numVertices; ++i)
  135. shape->SetVertex(i, object->GetPoint(i));
  136. shape->SetFriction(0.8f);
  137. if (object->HasProperty("Friction"))
  138. shape->SetFriction(ToFloat(object->GetProperty("Friction")));
  139. return shape;
  140. }
  141. void Sample2D::CreatePolyLineShape(Node* node, TileMapObject2D* object)
  142. {
  143. /*
  144. auto* shape = node->CreateComponent<CollisionChain2D>();
  145. int numVertices = object->GetNumPoints();
  146. shape->SetVertexCount(numVertices);
  147. for (int i = 0; i < numVertices; ++i)
  148. shape->SetVertex(i, object->GetPoint(i));
  149. shape->SetFriction(0.8f);
  150. if (object->HasProperty("Friction"))
  151. shape->SetFriction(ToFloat(object->GetProperty("Friction")));
  152. return shape;
  153. */
  154. // Latest Box2D supports only one sided chains with ghost vertices, use two sided edges instead.
  155. // But this can cause stuck at the edges ends https://box2d.org/posts/2020/06/ghost-collisions/
  156. u32 numVertices = object->GetNumPoints();
  157. for (u32 i = 1; i < numVertices; ++i)
  158. {
  159. CollisionEdge2D* shape = node->CreateComponent<CollisionEdge2D>();
  160. shape->SetVertices(object->GetPoint(i - 1), object->GetPoint(i));
  161. shape->SetFriction(0.8f);
  162. if (object->HasProperty("Friction"))
  163. shape->SetFriction(ToFloat(object->GetProperty("Friction")));
  164. }
  165. }
  166. Node* Sample2D::CreateCharacter(const TileMapInfo2D& info, float friction, const Vector3& position, float scale)
  167. {
  168. auto* cache = GetSubsystem<ResourceCache>();
  169. Node* spriteNode = scene_->CreateChild("Imp");
  170. spriteNode->SetPosition(position);
  171. spriteNode->SetScale(scale);
  172. auto* animatedSprite = spriteNode->CreateComponent<AnimatedSprite2D>();
  173. // Get scml file and Play "idle" anim
  174. auto* animationSet = cache->GetResource<AnimationSet2D>("Urho2D/imp/imp.scml");
  175. animatedSprite->SetAnimationSet(animationSet);
  176. animatedSprite->SetAnimation("idle");
  177. animatedSprite->SetLayer(3); // Put character over tile map (which is on layer 0) and over Orcs (which are on layer 2)
  178. auto* impBody = spriteNode->CreateComponent<RigidBody2D>();
  179. impBody->SetBodyType(BT_DYNAMIC);
  180. impBody->SetAllowSleep(false);
  181. impBody->SetFixedRotation(true);
  182. auto* shape = spriteNode->CreateComponent<CollisionCircle2D>();
  183. shape->SetRadius(1.1f); // Set shape size
  184. shape->SetFriction(friction); // Set friction
  185. shape->SetRestitution(0.1f); // Bounce
  186. shape->SetDensity(6.6f);
  187. return spriteNode;
  188. }
  189. Node* Sample2D::CreateTrigger()
  190. {
  191. Node* node = scene_->CreateChild(); // Clones will be renamed according to object type
  192. auto* body = node->CreateComponent<RigidBody2D>();
  193. body->SetBodyType(BT_STATIC);
  194. auto* shape = node->CreateComponent<CollisionBox2D>(); // Create box shape
  195. shape->SetTrigger(true);
  196. return node;
  197. }
  198. Node* Sample2D::CreateEnemy()
  199. {
  200. auto* cache = GetSubsystem<ResourceCache>();
  201. Node* node = scene_->CreateChild("Enemy");
  202. auto* staticSprite = node->CreateComponent<StaticSprite2D>();
  203. staticSprite->SetSprite(cache->GetResource<Sprite2D>("Urho2D/Aster.png"));
  204. auto* body = node->CreateComponent<RigidBody2D>();
  205. body->SetBodyType(BT_STATIC);
  206. auto* shape = node->CreateComponent<CollisionCircle2D>(); // Create circle shape
  207. shape->SetRadius(0.25f); // Set radius
  208. return node;
  209. }
  210. Node* Sample2D::CreateOrc()
  211. {
  212. auto* cache = GetSubsystem<ResourceCache>();
  213. Node* node = scene_->CreateChild("Orc");
  214. node->SetScale(scene_->GetChild("Imp", true)->GetScale());
  215. auto* animatedSprite = node->CreateComponent<AnimatedSprite2D>();
  216. auto* animationSet = cache->GetResource<AnimationSet2D>("Urho2D/Orc/Orc.scml");
  217. animatedSprite->SetAnimationSet(animationSet);
  218. animatedSprite->SetAnimation("run"); // Get scml file and Play "run" anim
  219. animatedSprite->SetLayer(2); // Make orc always visible
  220. auto* body = node->CreateComponent<RigidBody2D>();
  221. auto* shape = node->CreateComponent<CollisionCircle2D>();
  222. shape->SetRadius(1.3f); // Set shape size
  223. shape->SetTrigger(true);
  224. return node;
  225. }
  226. Node* Sample2D::CreateCoin()
  227. {
  228. auto* cache = GetSubsystem<ResourceCache>();
  229. Node* node = scene_->CreateChild("Coin");
  230. node->SetScale(0.5);
  231. auto* animatedSprite = node->CreateComponent<AnimatedSprite2D>();
  232. auto* animationSet = cache->GetResource<AnimationSet2D>("Urho2D/GoldIcon.scml");
  233. animatedSprite->SetAnimationSet(animationSet); // Get scml file and Play "idle" anim
  234. animatedSprite->SetAnimation("idle");
  235. animatedSprite->SetLayer(4);
  236. auto* body = node->CreateComponent<RigidBody2D>();
  237. body->SetBodyType(BT_STATIC);
  238. auto* shape = node->CreateComponent<CollisionCircle2D>(); // Create circle shape
  239. shape->SetRadius(0.32f); // Set radius
  240. shape->SetTrigger(true);
  241. return node;
  242. }
  243. Node* Sample2D::CreateMovingPlatform()
  244. {
  245. auto* cache = GetSubsystem<ResourceCache>();
  246. Node* node = scene_->CreateChild("MovingPlatform");
  247. node->SetScale(Vector3(3.0f, 1.0f, 0.0f));
  248. auto* staticSprite = node->CreateComponent<StaticSprite2D>();
  249. staticSprite->SetSprite(cache->GetResource<Sprite2D>("Urho2D/Box.png"));
  250. auto* body = node->CreateComponent<RigidBody2D>();
  251. body->SetBodyType(BT_STATIC);
  252. auto* shape = node->CreateComponent<CollisionBox2D>(); // Create box shape
  253. shape->SetSize(Vector2(0.32f, 0.32f)); // Set box size
  254. shape->SetFriction(0.8f); // Set friction
  255. return node;
  256. }
  257. void Sample2D::PopulateMovingEntities(TileMapLayer2D* movingEntitiesLayer)
  258. {
  259. // Create enemy (will be cloned at each placeholder)
  260. Node* enemyNode = CreateEnemy();
  261. Node* orcNode = CreateOrc();
  262. Node* platformNode = CreateMovingPlatform();
  263. // Instantiate enemies and moving platforms at each placeholder (placeholders are Poly Line objects defining a path from points)
  264. for (unsigned i=0; i < movingEntitiesLayer->GetNumObjects(); ++i)
  265. {
  266. // Get placeholder object
  267. TileMapObject2D* movingObject = movingEntitiesLayer->GetObject(i); // Get placeholder object
  268. if (movingObject->GetObjectType() == OT_POLYLINE)
  269. {
  270. // Clone the enemy and position it at placeholder point
  271. Node* movingClone;
  272. Vector2 offset = Vector2(0.0f, 0.0f);
  273. if (movingObject->GetType() == "Enemy")
  274. {
  275. movingClone = enemyNode->Clone();
  276. offset = Vector2(0.0f, -0.32f);
  277. }
  278. else if (movingObject->GetType() == "Orc")
  279. movingClone = orcNode->Clone();
  280. else if (movingObject->GetType() == "MovingPlatform")
  281. movingClone = platformNode->Clone();
  282. else
  283. continue;
  284. movingClone->SetPosition2D(movingObject->GetPoint(0) + offset);
  285. // Create script object that handles entity translation along its path
  286. auto* mover = movingClone->CreateComponent<Mover>();
  287. // Set path from points
  288. PODVector<Vector2> path = CreatePathFromPoints(movingObject, offset);
  289. mover->path_ = path;
  290. // Override default speed
  291. if (movingObject->HasProperty("Speed"))
  292. mover->speed_ = ToFloat(movingObject->GetProperty("Speed"));
  293. }
  294. }
  295. // Remove nodes used for cloning purpose
  296. enemyNode->Remove();
  297. orcNode->Remove();
  298. platformNode->Remove();
  299. }
  300. void Sample2D::PopulateCoins(TileMapLayer2D* coinsLayer)
  301. {
  302. // Create coin (will be cloned at each placeholder)
  303. Node* coinNode = CreateCoin();
  304. // Instantiate coins to pick at each placeholder
  305. for (unsigned i=0; i < coinsLayer->GetNumObjects(); ++i)
  306. {
  307. TileMapObject2D* coinObject = coinsLayer->GetObject(i); // Get placeholder object
  308. Node* coinClone = coinNode->Clone();
  309. coinClone->SetPosition2D(coinObject->GetPosition() + coinObject->GetSize() / 2 + Vector2(0.0f, 0.16f));
  310. }
  311. // Remove node used for cloning purpose
  312. coinNode->Remove();
  313. }
  314. void Sample2D::PopulateTriggers(TileMapLayer2D* triggersLayer)
  315. {
  316. // Create trigger node (will be cloned at each placeholder)
  317. Node* triggerNode = CreateTrigger();
  318. // Instantiate triggers at each placeholder (Rectangle objects)
  319. for (unsigned i=0; i < triggersLayer->GetNumObjects(); ++i)
  320. {
  321. TileMapObject2D* triggerObject = triggersLayer->GetObject(i); // Get placeholder object
  322. if (triggerObject->GetObjectType() == OT_RECTANGLE)
  323. {
  324. Node* triggerClone = triggerNode->Clone();
  325. triggerClone->SetName(triggerObject->GetType());
  326. auto* shape = triggerClone->GetComponent<CollisionBox2D>();
  327. shape->SetSize(triggerObject->GetSize());
  328. triggerClone->SetPosition2D(triggerObject->GetPosition() + triggerObject->GetSize() / 2);
  329. }
  330. }
  331. }
  332. float Sample2D::Zoom(Camera* camera)
  333. {
  334. auto* input = GetSubsystem<Input>();
  335. float zoom_ = camera->GetZoom();
  336. if (input->GetMouseMoveWheel() != 0)
  337. {
  338. zoom_ = Clamp(zoom_ + input->GetMouseMoveWheel() * 0.1f, CAMERA_MIN_DIST, CAMERA_MAX_DIST);
  339. camera->SetZoom(zoom_);
  340. }
  341. if (input->GetKeyDown(KEY_PAGEUP))
  342. {
  343. zoom_ = Clamp(zoom_ * 1.01f, CAMERA_MIN_DIST, CAMERA_MAX_DIST);
  344. camera->SetZoom(zoom_);
  345. }
  346. if (input->GetKeyDown(KEY_PAGEDOWN))
  347. {
  348. zoom_ = Clamp(zoom_ * 0.99f, CAMERA_MIN_DIST, CAMERA_MAX_DIST);
  349. camera->SetZoom(zoom_);
  350. }
  351. return zoom_;
  352. }
  353. PODVector<Vector2> Sample2D::CreatePathFromPoints(TileMapObject2D* object, const Vector2& offset)
  354. {
  355. PODVector<Vector2> path;
  356. for (unsigned i=0; i < object->GetNumPoints(); ++i)
  357. path.Push(object->GetPoint(i) + offset);
  358. return path;
  359. }
  360. void Sample2D::CreateUIContent(const String& demoTitle, int remainingLifes, int remainingCoins)
  361. {
  362. auto* cache = GetSubsystem<ResourceCache>();
  363. auto* ui = GetSubsystem<UI>();
  364. // Set the default UI style and font
  365. ui->GetRoot()->SetDefaultStyle(cache->GetResource<XMLFile>("UI/DefaultStyle.xml"));
  366. auto* font = cache->GetResource<Font>("Fonts/Anonymous Pro.ttf");
  367. // We create in-game UIs (coins and lifes) first so that they are hidden by the fullscreen UI (we could also temporary hide them using SetVisible)
  368. // Create the UI for displaying the remaining coins
  369. auto* coinsUI = ui->GetRoot()->CreateChild<BorderImage>("Coins");
  370. coinsUI->SetTexture(cache->GetResource<Texture2D>("Urho2D/GoldIcon.png"));
  371. coinsUI->SetSize(50, 50);
  372. coinsUI->SetImageRect(IntRect(0, 64, 60, 128));
  373. coinsUI->SetAlignment(HA_LEFT, VA_TOP);
  374. coinsUI->SetPosition(5, 5);
  375. auto* coinsText = coinsUI->CreateChild<Text>("CoinsText");
  376. coinsText->SetAlignment(HA_CENTER, VA_CENTER);
  377. coinsText->SetFont(font, 24);
  378. coinsText->SetTextEffect(TE_SHADOW);
  379. coinsText->SetText(String(remainingCoins));
  380. // Create the UI for displaying the remaining lifes
  381. auto* lifeUI = ui->GetRoot()->CreateChild<BorderImage>("Life");
  382. lifeUI->SetTexture(cache->GetResource<Texture2D>("Urho2D/imp/imp_all.png"));
  383. lifeUI->SetSize(70, 80);
  384. lifeUI->SetAlignment(HA_RIGHT, VA_TOP);
  385. lifeUI->SetPosition(-5, 5);
  386. auto* lifeText = lifeUI->CreateChild<Text>("LifeText");
  387. lifeText->SetAlignment(HA_CENTER, VA_CENTER);
  388. lifeText->SetFont(font, 24);
  389. lifeText->SetTextEffect(TE_SHADOW);
  390. lifeText->SetText(String(remainingLifes));
  391. // Create the fullscreen UI for start/end
  392. auto* fullUI = ui->GetRoot()->CreateChild<Window>("FullUI");
  393. fullUI->SetStyleAuto();
  394. fullUI->SetSize(ui->GetRoot()->GetWidth(), ui->GetRoot()->GetHeight());
  395. fullUI->SetEnabled(false); // Do not react to input, only the 'Exit' and 'Play' buttons will
  396. // Create the title
  397. auto* title = fullUI->CreateChild<BorderImage>("Title");
  398. title->SetMinSize(fullUI->GetWidth(), 50);
  399. title->SetTexture(cache->GetResource<Texture2D>("Textures/HeightMap.png"));
  400. title->SetFullImageRect();
  401. title->SetAlignment(HA_CENTER, VA_TOP);
  402. auto* titleText = title->CreateChild<Text>("TitleText");
  403. titleText->SetAlignment(HA_CENTER, VA_CENTER);
  404. titleText->SetFont(font, 24);
  405. titleText->SetText(demoTitle);
  406. // Create the image
  407. auto* spriteUI = fullUI->CreateChild<BorderImage>("Sprite");
  408. spriteUI->SetTexture(cache->GetResource<Texture2D>("Urho2D/imp/imp_all.png"));
  409. spriteUI->SetSize(238, 271);
  410. spriteUI->SetAlignment(HA_CENTER, VA_CENTER);
  411. spriteUI->SetPosition(0, - ui->GetRoot()->GetHeight() / 4);
  412. // Create the 'EXIT' button
  413. auto* exitButton = ui->GetRoot()->CreateChild<Button>("ExitButton");
  414. exitButton->SetStyleAuto();
  415. exitButton->SetFocusMode(FM_RESETFOCUS);
  416. exitButton->SetSize(100, 50);
  417. exitButton->SetAlignment(HA_CENTER, VA_CENTER);
  418. exitButton->SetPosition(-100, 0);
  419. auto* exitText = exitButton->CreateChild<Text>("ExitText");
  420. exitText->SetAlignment(HA_CENTER, VA_CENTER);
  421. exitText->SetFont(font, 24);
  422. exitText->SetText("EXIT");
  423. SubscribeToEvent(exitButton, E_RELEASED, URHO3D_HANDLER(Sample2D, HandleExitButton));
  424. // Create the 'PLAY' button
  425. auto* playButton = ui->GetRoot()->CreateChild<Button>("PlayButton");
  426. playButton->SetStyleAuto();
  427. playButton->SetFocusMode(FM_RESETFOCUS);
  428. playButton->SetSize(100, 50);
  429. playButton->SetAlignment(HA_CENTER, VA_CENTER);
  430. playButton->SetPosition(100, 0);
  431. auto* playText = playButton->CreateChild<Text>("PlayText");
  432. playText->SetAlignment(HA_CENTER, VA_CENTER);
  433. playText->SetFont(font, 24);
  434. playText->SetText("PLAY");
  435. // SubscribeToEvent(playButton, E_RELEASED, HANDLER(Urho2DPlatformer, HandlePlayButton));
  436. // Create the instructions
  437. auto* instructionText = ui->GetRoot()->CreateChild<Text>("Instructions");
  438. instructionText->SetText("Use WASD keys or Arrows to move\nPageUp/PageDown/MouseWheel to zoom\nF5/F7 to save/reload scene\n'Z' to toggle debug geometry\nSpace to fight");
  439. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  440. instructionText->SetTextAlignment(HA_CENTER); // Center rows in relation to each other
  441. instructionText->SetAlignment(HA_CENTER, VA_CENTER);
  442. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  443. // Show mouse cursor
  444. auto* input = GetSubsystem<Input>();
  445. input->SetMouseVisible(true);
  446. }
  447. void Sample2D::HandleExitButton(StringHash eventType, VariantMap& eventData)
  448. {
  449. auto* engine = GetSubsystem<Engine>();
  450. engine->Exit();
  451. }
  452. void Sample2D::SaveScene(bool initial)
  453. {
  454. String filename = demoFilename_;
  455. if (!initial)
  456. filename += "InGame";
  457. File saveFile(context_, GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Scenes/" + filename + ".xml", FILE_WRITE);
  458. scene_->SaveXML(saveFile);
  459. }
  460. void Sample2D::CreateBackgroundSprite(const TileMapInfo2D& info, float scale, const String& texture, bool animate)
  461. {
  462. auto* cache = GetSubsystem<ResourceCache>();
  463. Node* node = scene_->CreateChild("Background");
  464. node->SetPosition(Vector3(info.GetMapWidth(), info.GetMapHeight(), 0) / 2);
  465. node->SetScale(scale);
  466. auto* sprite = node->CreateComponent<StaticSprite2D>();
  467. sprite->SetSprite(cache->GetResource<Sprite2D>(texture));
  468. SetRandomSeed(Time::GetSystemTime()); // Randomize from system clock
  469. sprite->SetColor(Color(Random(0.0f, 1.0f), Random(0.0f, 1.0f), Random(0.0f, 1.0f), 1.0f));
  470. sprite->SetLayer(-99);
  471. // Create rotation animation
  472. if (animate)
  473. {
  474. SharedPtr<ValueAnimation> animation(new ValueAnimation(context_));
  475. animation->SetKeyFrame(0, Variant(Quaternion(0.0f, 0.0f, 0.0f)));
  476. animation->SetKeyFrame(1, Variant(Quaternion(0.0f, 0.0f, 180.0f)));
  477. animation->SetKeyFrame(2, Variant(Quaternion(0.0f, 0.0f, 0.0f)));
  478. node->SetAttributeAnimation("Rotation", animation, WM_LOOP, 0.05f);
  479. }
  480. }
  481. void Sample2D::SpawnEffect(Node* node)
  482. {
  483. auto* cache = GetSubsystem<ResourceCache>();
  484. Node* particleNode = node->CreateChild("Emitter");
  485. particleNode->SetScale(0.5f / node->GetScale().x_);
  486. auto* particleEmitter = particleNode->CreateComponent<ParticleEmitter2D>();
  487. particleEmitter->SetLayer(2);
  488. particleEmitter->SetEffect(cache->GetResource<ParticleEffect2D>("Urho2D/sun.pex"));
  489. }
  490. void Sample2D::PlaySoundEffect(const String& soundName)
  491. {
  492. auto* cache = GetSubsystem<ResourceCache>();
  493. auto* source = scene_->CreateComponent<SoundSource>();
  494. auto* sound = cache->GetResource<Sound>("Sounds/" + soundName);
  495. if (sound != nullptr) {
  496. source->SetAutoRemoveMode(REMOVE_COMPONENT);
  497. source->Play(sound);
  498. }
  499. }