SFML и C++ Уроки \ Разработка игр › Форумы › SFML Graphics › Tile Map Editor › Ответ в теме: Tile Map Editor
Так, окей значит я поставил файл mainmap.tmx в папку images где лежит картинка карты и все поменялось, больше не пишет старую проблему, но теперь пишет failed to load image “map.png”. Reason unable to open the file. , зайдя в tile map editor поменял расположение файла map.png. В той строке (где в блокноте открывать mainmap.tmx): <image source=”map.png”… Если ставлю по другому то tile map не видит и просит указать путь к файлу (когда в программе указываю путь к своему файлу: tile map сам оставляет <image source=”map.png”…)
Вот информация детальная: значит вот путь до mainmap.tmx и map.png:
C:\Users\spoty\Documents\Visual Studio 2013\Projects\Adventures\Adventures\images
Вот код:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 |
#include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include "view.h" #include <iostream> #include <sstream> #include "mission.h" #include "iostream" #include "level.h" #include <vector> #include <list> #include "tinyxml\tinyxml.h" using namespace sf; class Entity { public: std::vector<Object> obj; float dx, dy, x, y, speed, moveTimer; int w, h, health; bool life, isMove, onGround; Texture texture; Sprite sprite; String name; Entity(Image &image, float X, float Y, int W, int H, String Name) { x = X; y = Y; w = W; h = H; name = Name; moveTimer = 0; speed = 0; health = 100; dx = 0; dy = 0; life = true; onGround = false; isMove = false; texture.loadFromImage(image); sprite.setTexture(texture); sprite.setOrigin(w / 2, h / 2); } FloatRect getRect(){ return FloatRect(x, y, w, h); } }; class Player :public Entity { public: enum { left, right, jump, stay } state; int playerScore; Player(Image &image, Level &lev, float X, float Y, int W, int H, String Name) :Entity(image, X, Y, W, H, Name){ playerScore = 0; state = stay; obj = lev.GetAllObjects(); if (name == "Player1"){ sprite.setTextureRect(IntRect(97, 227, w, h)); } } void control() { if (life == true) { if (Keyboard::isKeyPressed(Keyboard::A)) { state = left; speed = 0.3; } if (Keyboard::isKeyPressed(Keyboard::D)) { state = right; speed = 0.3; } if ((Keyboard::isKeyPressed(Keyboard::Space) && (onGround == true))) { state = jump; dy = -0.5; onGround = false; } } } void update(float time) { control(); switch (state) { case left: dx = -speed; break; case right: dx = speed; break; case jump: break; case stay: break; } x += dx*time; checkCollisionWithMap(dx, 0); y += dy*time; checkCollisionWithMap(0, dy); if (!isMove) speed = 0; sprite.setPosition(x + w / 2, y + h / 2); if (health <= 0) { life = false; } if (life == true) { getplayercoordinateforview(x, y); } dy = dy + 0.0015*time; } float getplayercoordinateX() { return x; } void checkCollisionWithMap(float Dx, float Dy) { for (int i = 0; i<obj.size(); i++) if (getRect().intersects(obj[i].rect)) { if (obj[i].name == "solid") { if (Dy>0) { y = obj[i].rect.top - h; dy = 0; onGround = true; } if (Dy<0) { y = obj[i].rect.top + obj[i].rect.height; dy = 0; } if (Dx>0) { x = obj[i].rect.left - w; } if (Dx<0) { x = obj[i].rect.left + obj[i].rect.width; } } } } }; class Enemy :public Entity{ public: Enemy(Image &image, Level &lvl, float X, float Y, int W, int H, String Name) :Entity(image, X, Y, W, H, Name) { obj = lvl.GetObjects("solid"); if (name == "EasyEnemy") { sprite.setTextureRect(IntRect(0, 0, w, h)); dx = 0.1; } } void checkCollisionWithMap(float Dx, float Dy) { for (int i = 0; i<obj.size(); i++) if (getRect().intersects(obj[i].rect)) { if (Dy>0) { y = obj[i].rect.top - h; dy = 0; onGround = true; } if (Dy<0) { y = obj[i].rect.top + obj[i].rect.height; dy = 0; } if (Dx>0) { x = obj[i].rect.left - w; dx = -0.1; sprite.scale(-1, 1); } if (Dx<0) { x = obj[i].rect.left + obj[i].rect.width; dx = 0.1; sprite.scale(-1, 1); } } } void update(float time) { if (name == "EasyEnemy") { //moveTime += time; if (moveTimer>3000) {dx*=-1; moveTimer = 0; } checkCollisionWithMap(dx, 0); x += dx*time; sprite.setPosition(x + w / 2, y + h / 2); // ЭТО КСТАТИ ЗАДАЕТ ПОЗИЦИЮ СПРАЙТА В КГО ЦЕНТР if (health <= 0) { life = false; } } } }; int main() { sf::RenderWindow window(sf::VideoMode(1980, 1080), "Glinskii Adventures"); view.reset(sf::FloatRect(0, 0, 640, 400)); Level lvl; lvl.LoadFromFile("images/mainmap.tmx"); Image heroImage; heroImage.loadFromFile("images/hero.png"); heroImage.createMaskFromColor(Color(41, 33, 59)); Image easyEnemyImage; easyEnemyImage.loadFromFile("images/enemy1.jpg"); easyEnemyImage.createMaskFromColor(Color(255, 255, 255)); /*Image map_image; map_image.loadFromFile("images/map.png"); Texture map; map.loadFromImage(map_image); Sprite map_sprite; map_sprite.setTexture(map); Image house_image; house_image.loadFromFile("images/house.png"); house_image.createMaskFromColor(Color(255, 255, 255)); Texture house; house.loadFromImage(house_image); Sprite house_sprite; house_sprite.setTexture(house); house_sprite.setPosition(80, 539);*/ Image quest_image; quest_image.loadFromFile("images/tab.jpg"); Texture quest_texture; quest_texture.loadFromImage(quest_image); Sprite s_quest; s_quest.setTexture(quest_texture); s_quest.setTextureRect(IntRect(0, 0, 224, 352)); /*Image map2; map2.loadFromFile("images/map2.png"); Texture map2texture; map2texture.loadFromImage(map2); Sprite map2s; map2s.setTexture(map2texture);*/ Object player = lvl.GetObject("player"); Object easyEnemyObject = lvl.GetObject("easyEnemy"); SoundBuffer claySongBuffer; claySongBuffer.loadFromFile("sounds/claySong.ogg"); Sound claySong(claySongBuffer); claySong.play(); claySong.setLoop(true); /*SoundBuffer deathBuffer; deathBuffer.loadFromFile("sounds/deathS.ogg"); Sound deathS(deathBuffer); deathS.setVolume(100); Music death; death.openFromFile("music/death.ogg"); death.setVolume(50);*/ /*SoundBuffer lowhpBuffer; lowhpBuffer.loadFromFile("sounds/lowhp.ogg"); Sound lowhp(lowhpBuffer);*/ /*SoundBuffer walkBuffer; walkBuffer.loadFromFile("sounds/walk.ogg"); Sound walk(walkBuffer); walk.setVolume(100);*/ Music soundtrack; soundtrack.openFromFile("music/soundtrack.ogg"); soundtrack.setVolume(50); soundtrack.play(); soundtrack.setLoop(true); Music soundtrack2; soundtrack2.openFromFile("music/soundtrack2.ogg"); soundtrack2.setVolume(100); Font font; font.loadFromFile("fonts/classic.TTF"); Text text("", font, 20); text.setStyle(Text::Bold); Text pickText("", font, 20); pickText.setStyle(Text::Bold); Text text2("", font, 20); text2.setStyle(Text::Bold); Text glinPlate("", font, 20); glinPlate.setStyle(Text::Bold); glinPlate.setStyle(Text::Underlined); Text nickname("", font, 20); Player p(heroImage, lvl, player.rect.left, player.rect.top, 94, 59, "Player1"); Enemy easyEnemy(easyEnemyImage, lvl, easyEnemyObject.rect.left, easyEnemyObject.rect.top, 79, 59, "EasyEnemy"); float CurrentFrame = 0; Clock clock; Clock gameTimeClock; int gameTime = 0; bool showMissionText = true; while (window.isOpen()) { float time = clock.getElapsedTime().asMicroseconds(); if (p.life == true) gameTime = gameTimeClock.getElapsedTime().asSeconds(); else { p.sprite.setColor(Color(235, 65, 7)); view.zoom(1.0090); view.move(0, 0.07); view.move(0.07, 0); view.rotate(1); } clock.restart(); time = time / 800; sf::Event event; while (window.pollEvent(event)) { window.setKeyRepeatEnabled(false); if (event.type == sf::Event::Closed) window.close(); /*if (p.life == true) { if ((event.type == Event::KeyPressed) && (event.key.code == Keyboard::D)) { walk.play(); } }*/ /*if (death.getStatus() == Sound::Playing) { continue; } else { soundtrack.stop(); claySong.stop(); death.play(); deathS.play(); }*/ if (event.type == Event::KeyPressed) if ((event.key.code == Keyboard::Tab)) { switch (showMissionText) { case true: { std::ostringstream task; task << getTextMission(getCurrentMission(p.getplayercoordinateX())); text2.setString("\n" + task.str()); showMissionText = false; glinPlate.setString("Глиняная плита гласит:"); nickname.setString("XxX_Daun_XxX"); break; } case false: { text2.setString(""); showMissionText = true; break; } } } } p.update(time); easyEnemy.update(time); changeview(); window.setView(view); window.clear(); lvl.Draw(window); std::ostringstream playerHealthString, gameTimeString; playerHealthString << p.health; gameTimeString << gameTime; text.setString("Здоровье: " + playerHealthString.str() + "\nВремя игры: " + gameTimeString.str()); text.setPosition(view.getCenter().x - 315, view.getCenter().y - 200); window.draw(text); std::ostringstream playerScoreString; playerScoreString << p.playerScore; pickText.setString("Собрано: " + playerScoreString.str()); pickText.setPosition(view.getCenter().x + 140, view.getCenter().y - 200); window.draw(pickText); if (!showMissionText) { text2.setPosition(view.getCenter().x - 315, view.getCenter().y - 100); s_quest.setPosition(view.getCenter().x - 320, view.getCenter().y - 100); glinPlate.setPosition(view.getCenter().x - 315, view.getCenter().y - 100); nickname.setPosition(view.getCenter().x - 20, view.getCenter().y); window.draw(s_quest); window.draw(text2); window.draw(glinPlate); window.draw(nickname); } window.draw(easyEnemy.sprite); window.draw(p.sprite); window.display(); } return 0; } |
Вот файл level.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 |
#ifndef LEVEL_H #define LEVEL_H #include <string> #include <vector> #include <map> #include <SFML/Graphics.hpp> #include <iostream> #include "tinyxml/tinyxml.h" struct Object { int GetPropertyInt(std::string name);//номер свойства объекта в нашем списке float GetPropertyFloat(std::string name); std::string GetPropertyString(std::string name); std::string name;//объявили переменную name типа string std::string type;//а здесь переменную type типа string sf::Rect<float> rect;//тип Rect с нецелыми значениями std::map<std::string, std::string> properties;//создаём ассоциатиный массив. ключ - строковый тип, значение - строковый sf::Sprite sprite;//объявили спрайт }; struct Layer//слои { int opacity;//непрозрачность слоя std::vector<sf::Sprite> tiles;//закидываем в вектор тайлы }; class Level//главный класс - уровень { public: bool LoadFromFile(std::string filename);//возвращает false если не получилось загрузить Object GetObject(std::string name); std::vector<Object> GetObjects(std::string name);//выдаем объект в наш уровень std::vector<Object> GetAllObjects();//выдаем все объекты в наш уровень void Draw(sf::RenderWindow &window);//рисуем в окно sf::Vector2i GetTileSize();//получаем размер тайла private: int width, height, tileWidth, tileHeight;//в tmx файле width height в начале,затем размер тайла int firstTileID;//получаем айди первого тайла sf::Rect<float> drawingBounds;//размер части карты которую рисуем sf::Texture tilesetImage;//текстура карты std::vector<Object> objects;//массив типа Объекты, который мы создали std::vector<Layer> layers; }; /////////////////////////////////////// int Object::GetPropertyInt(std::string name)//возвращаем номер свойства в нашем списке { return atoi(properties[name].c_str()); } float Object::GetPropertyFloat(std::string name) { return strtod(properties[name].c_str(), NULL); } std::string Object::GetPropertyString(std::string name)//получить имя в виде строки.вроде понятно { return properties[name]; } bool Level::LoadFromFile(std::string filename)//двоеточия-обращение к методам класса вне класса { TiXmlDocument levelFile(filename.c_str());//загружаем файл в TiXmlDocument // загружаем XML-карту if (!levelFile.LoadFile())//если не удалось загрузить карту { std::cout << "Loading level \"" << filename << "\" failed." << std::endl;//выдаем ошибку return false; } // работаем с контейнером map TiXmlElement *map; map = levelFile.FirstChildElement("map"); // пример карты: <map version="1.0" orientation="orthogonal" // width="10" height="10" tilewidth="34" tileheight="34"> width = atoi(map->Attribute("width"));//извлекаем из нашей карты ее свойства height = atoi(map->Attribute("height"));//те свойства, которые задавали при работе в tileWidth = atoi(map->Attribute("tilewidth"));//тайлмап редакторе tileHeight = atoi(map->Attribute("tileheight")); // Берем описание тайлсета и идентификатор первого тайла TiXmlElement *tilesetElement; tilesetElement = map->FirstChildElement("tileset"); firstTileID = atoi(tilesetElement->Attribute("firstgid")); // source - путь до картинки в контейнере image TiXmlElement *image; image = tilesetElement->FirstChildElement("image"); std::string imagepath = image->Attribute("source"); // пытаемся загрузить тайлсет sf::Image img; if (!img.loadFromFile(imagepath)) { std::cout << "Failed to load tile sheet." << std::endl;//если не удалось загрузить тайлсет-выводим ошибку в консоль return false; } img.createMaskFromColor(sf::Color(255, 255, 255));//для маски цвета.сейчас нет маски tilesetImage.loadFromImage(img); tilesetImage.setSmooth(false);//сглаживание // получаем количество столбцов и строк тайлсета int columns = tilesetImage.getSize().x / tileWidth; int rows = tilesetImage.getSize().y / tileHeight; // вектор из прямоугольников изображений (TextureRect) std::vector<sf::Rect<int>> subRects; for (int y = 0; y < rows; y++) for (int x = 0; x < columns; x++) { sf::Rect<int> rect; rect.top = y * tileHeight; rect.height = tileHeight; rect.left = x * tileWidth; rect.width = tileWidth; subRects.push_back(rect); } // работа со слоями TiXmlElement *layerElement; layerElement = map->FirstChildElement("layer"); while (layerElement) { Layer layer; // если присутствует opacity, то задаем прозрачность слоя, иначе он полностью непрозрачен if (layerElement->Attribute("opacity") != NULL) { float opacity = strtod(layerElement->Attribute("opacity"), NULL); layer.opacity = 255 * opacity; } else { layer.opacity = 255; } // контейнер <data> TiXmlElement *layerDataElement; layerDataElement = layerElement->FirstChildElement("data"); if (layerDataElement == NULL) { std::cout << "Bad map. No layer information found." << std::endl; } // контейнер <tile> - описание тайлов каждого слоя TiXmlElement *tileElement; tileElement = layerDataElement->FirstChildElement("tile"); if (tileElement == NULL) { std::cout << "Bad map. No tile information found." << std::endl; return false; } int x = 0; int y = 0; while (tileElement) { int tileGID = atoi(tileElement->Attribute("gid")); int subRectToUse = tileGID - firstTileID; // Устанавливаем TextureRect каждого тайла if (subRectToUse >= 0) { sf::Sprite sprite; sprite.setTexture(tilesetImage); sprite.setTextureRect(subRects[subRectToUse]); sprite.setPosition(x * tileWidth, y * tileHeight); sprite.setColor(sf::Color(255, 255, 255, layer.opacity)); layer.tiles.push_back(sprite);//закидываем в слой спрайты тайлов } tileElement = tileElement->NextSiblingElement("tile"); x++; if (x >= width) { x = 0; y++; if (y >= height) y = 0; } } layers.push_back(layer); layerElement = layerElement->NextSiblingElement("layer"); } // работа с объектами TiXmlElement *objectGroupElement; // если есть слои объектов if (map->FirstChildElement("objectgroup") != NULL) { objectGroupElement = map->FirstChildElement("objectgroup"); while (objectGroupElement) { // контейнер <object> TiXmlElement *objectElement; objectElement = objectGroupElement->FirstChildElement("object"); while (objectElement) { // получаем все данные - тип, имя, позиция, и тд std::string objectType; if (objectElement->Attribute("type") != NULL) { objectType = objectElement->Attribute("type"); } std::string objectName; if (objectElement->Attribute("name") != NULL) { objectName = objectElement->Attribute("name"); } int x = atoi(objectElement->Attribute("x")); int y = atoi(objectElement->Attribute("y")); int width, height; sf::Sprite sprite; sprite.setTexture(tilesetImage); sprite.setTextureRect(sf::Rect<int>(0, 0, 0, 0)); sprite.setPosition(x, y); if (objectElement->Attribute("width") != NULL) { width = atoi(objectElement->Attribute("width")); height = atoi(objectElement->Attribute("height")); } else { width = subRects[atoi(objectElement->Attribute("gid")) - firstTileID].width; height = subRects[atoi(objectElement->Attribute("gid")) - firstTileID].height; sprite.setTextureRect(subRects[atoi(objectElement->Attribute("gid")) - firstTileID]); } // экземпляр объекта Object object; object.name = objectName; object.type = objectType; object.sprite = sprite; sf::Rect <float> objectRect; objectRect.top = y; objectRect.left = x; objectRect.height = height; objectRect.width = width; object.rect = objectRect; // "переменные" объекта TiXmlElement *properties; properties = objectElement->FirstChildElement("properties"); if (properties != NULL) { TiXmlElement *prop; prop = properties->FirstChildElement("property"); if (prop != NULL) { while (prop) { std::string propertyName = prop->Attribute("name"); std::string propertyValue = prop->Attribute("value"); object.properties[propertyName] = propertyValue; prop = prop->NextSiblingElement("property"); } } } objects.push_back(object); objectElement = objectElement->NextSiblingElement("object"); } objectGroupElement = objectGroupElement->NextSiblingElement("objectgroup"); } } else { std::cout << "No object layers found..." << std::endl; } return true; } Object Level::GetObject(std::string name) { // только первый объект с заданным именем for (int i = 0; i < objects.size(); i++) if (objects[i].name == name) return objects[i]; } std::vector<Object> Level::GetObjects(std::string name) { // все объекты с заданным именем std::vector<Object> vec; for (int i = 0; i < objects.size(); i++) if (objects[i].name == name) vec.push_back(objects[i]); return vec; } std::vector<Object> Level::GetAllObjects() { return objects; }; sf::Vector2i Level::GetTileSize() { return sf::Vector2i(tileWidth, tileHeight); } void Level::Draw(sf::RenderWindow &window) { // рисуем все тайлы (объекты не рисуем!) for (int layer = 0; layer < layers.size(); layer++) for (int tile = 0; tile < layers[layer].tiles.size(); tile++) window.draw(layers[layer].tiles[tile]); } #endif |