Sample2D.cpp 20 KB

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