SFML и C++ Уроки \ Разработка игр › Форумы › Логика игр › Загрузка карты из TileMap
В этой теме 1 ответ, 1 участник, последнее обновление Maksim 6 года/лет, 5 мес. назад.
Просмотр 2 сообщений - с 1 по 2 (из 2 всего)
-
АвторСообщения
-
Почему не загружается карта из тайлмэпа, вроде все сделал как в видео?
C++123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308#include <SFML/Graphics.hpp>#include <iostream>#include <sstream>//#include "map.h"#include "view.h"#include "mission.h"#include "level.h"#include <vector>using std::vector;using namespace sf;///////////////////////////////////////////////ГЛАВНЫЙ КЛАСС/////////////////////////////////////////////////////class Entity {public: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, String Name, float X, float Y, int W, int H) {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:int playerScore;enum stateObjekt { left, right, up, down, jump, stay };stateObjekt state;Player(Image &image, String Name, Level &lev, float X, float Y, int W, int H) :Entity(image, Name, X, Y, W, H) {playerScore = 0; state = stay; obj = lev.GetAllObjects();if (name == "Player1") {sprite.setTextureRect(IntRect(50, 550, w, h));}}void control() {if (Keyboard::isKeyPressed(Keyboard::Left)) {state = left;speed = 0.1;/*CurrentFrame += 0.005 * time;if (CurrentFrame > 2) CurrentFrame -= 2;p.sprite.setTextureRect(IntRect(46 * int(CurrentFrame), 0, 46, 45));*/}if (Keyboard::isKeyPressed(Keyboard::Right)) {state = right;speed = 0.1;/*CurrentFrame += 0.005 * time;if (CurrentFrame > 2) CurrentFrame -= 2;p.sprite.setTextureRect(IntRect(46 * int(CurrentFrame) + 46, 0, -46, 45));*/}if (Keyboard::isKeyPressed(Keyboard::Up) && onGround) {state = jump;dy = -0.5;onGround = false;speed = 0.1;/*CurrentFrame += 0.005 * time;if (CurrentFrame > 2) CurrentFrame -= 2;p.sprite.setTextureRect(IntRect(46 * int(CurrentFrame) + 46, 0, -46, 45));*/}if (Keyboard::isKeyPressed(Keyboard::Down)) {state = down;speed = 0.1;/*CurrentFrame += 0.005 * time;if (CurrentFrame > 2) CurrentFrame -= 2;p.sprite.setTextureRect(IntRect(46 * int(CurrentFrame) + 46, 0, -46, 45));*/}}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; }}}/*for (int i = y / 65; i < (y + h) / 65; i++)for (int j = x / 65; j<(x + w) / 65; j++){std::cout << "y = "<< y << ' ' << "\nx = " << x;if (TileMap[i][j] == '0'){if (Dy>0)y = i * 65 - h; dy = 0; onGround = true;if (Dy<0)y = i * 65 + 65; dy = 0;if (Dx>0)x = j * 65 - w;if (Dx<0)x = j * 65 + 65;}}*/}void update(float time){control();switch (state)//тут делаются различные действия в зависимости от состояния{case right: dx = speed; break;case left: dx = -speed; break;case up: break;case down: dx = 0; break;case jump: break;case stay: break;}x += dx*time;checkCollisionWithMap(dx, 0);//обрабатываем столкновение по Хy += dy*time;checkCollisionWithMap(0, dy);//обрабатываем столкновение по Yspeed = 0;sprite.setPosition(x + w / 2, y + h / 2); //задаем позицию спрайта в место его центраdy = dy + 0.0015*time; // делаем притяжение к землеif (health <= 0) { life = false; }if (life) {setPlayerCoordinateForView(x, y);}}};////////////////////////////////////////////////КЛАСС ВРАГОВ/////////////////////////////////////////////////class Enemy :public Entity {public:Enemy(Image &image, String Name, Level &lvl, float X, float Y, int W, int H) :Entity(image, Name, X, Y, W, H) {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 (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; 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); }}}/*for (int i = y / 65; i < (y + h) / 65; i++)for (int j = x / 65; j<(x + w) / 65; j++){if (TileMap[i][j] == '0'){if (Dy>0) {y = i * 65 - h; dy = 0; onGround = true;}if (Dy<0) {y = i * 65 + 65; dy = 0;}if (Dx>0) {x = j * 65 - w; dx = -0.1; sprite.scale(-1, 1);}if (Dx<0) {x = j * 65 + 65; dx = 0.1; sprite.scale(-1, 1);}}}*/}void update(float time){if (name == "EasyEnemy") {//для персонажа с таким именем логика будет такой//moveTimer += time;if (moveTimer>3000){ dx *= -1; moveTimer = 0; }//меняет направление примерно каждые 3 секx += dx*time;checkCollisionWithMap(dx, 0);y += dy*time;checkCollisionWithMap(0, dy);sprite.setPosition(x + w / 2, y + h / 2);dy = dy + 0.0015*time;if (health <= 0) {life = false;}}}};int main(){RenderWindow window(VideoMode(1000, 600), "Test");view.reset(FloatRect(0, 0, 800, 450));Font font;font.loadFromFile("CyrilicOld.ttf");Text text("", font, 20);text.setFillColor(Color::Black);Level lvl;lvl.LoadFromFile("MapForGame.tmx");Image map_image;map_image.loadFromFile("images/map.png");Texture map;map.loadFromImage(map_image);Sprite s_map;s_map.setTexture(map);Object player = lvl.GetObject("player");//объект игрока на нашей карте.задаем координаты игроку в начале при помощи негоObject easyEnemyObject = lvl.GetObject("easyEnemy");//объект легкого врага на нашей карте.задаем координаты игроку в начале при помощи негоImage heroImage;heroImage.loadFromFile("images/Hero.png");heroImage.createMaskFromColor(Color(48, 48, 48));Image easyEnemyImage;easyEnemyImage.loadFromFile("images/EasyEnemy.png");easyEnemyImage.createMaskFromColor(Color(0, 0, 0));Player p(heroImage, "Player1", lvl, player.rect.left, player.rect.top, 40, 30);//передаем координаты прямоугольника player из карты в координаты нашего игрокаEnemy easyEnemy(easyEnemyImage, "EasyEnemy", lvl, easyEnemyObject.rect.left, easyEnemyObject.rect.top, 200, 97);//передаем координаты прямоугольника easyEnemy из карты в координаты нашего врагаClock clock;Clock gameTimeClock;int gameTime = 0; //для счестчика игрового времениwhile (window.isOpen()){float time = clock.getElapsedTime().asMicroseconds();if (p.life)gameTime = gameTimeClock.getElapsedTime().asSeconds();else {view.zoom(1.0006f);view.rotate(0.2);}clock.restart();time = time / 800;Event event;while (window.pollEvent(event)){if (event.type == sf::Event::Closed)window.close();}p.update(time);easyEnemy.update(time);window.setView(view);window.clear();lvl.Draw(window); //рисуем карту тайлмэпаwindow.getSystemHandle();//СТАРАЯ КАРТА/*for (int i = 0; i < HEIGHT_MAP; i++)for (int j = 0; j < WIDTH_MAP; j++){if (TileMap[i][j] == ' ') s_map.setTextureRect(IntRect(65, 0, 65, 65));if (TileMap[i][j] == 's') s_map.setTextureRect(IntRect(130, 0, 65, 65));if ((TileMap[i][j] == '0')) s_map.setTextureRect(IntRect(0, 0, 65, 65));if ((TileMap[i][j] == 'f')) s_map.setTextureRect(IntRect(195, 0, 65, 65));if ((TileMap[i][j] == 'h')) s_map.setTextureRect(IntRect(260, 0, 65, 65));s_map.setPosition(j * 65, i * 65);window.draw(s_map);}*/std::ostringstream playerScoreString, playerHealthString, gameTimeString;playerScoreString << p.playerScore;playerHealthString << p.health;gameTimeString << gameTime;text.setString("Собрано червячков:" + playerScoreString.str() + "\nЗдоровье: " + playerHealthString.str() + "\nВремя в игре: " + gameTimeString.str());text.setPosition(view.getCenter().x - 370, view.getCenter().y - 200);window.draw(text);window.draw(p.sprite);window.draw(easyEnemy.sprite);window.display();}return 0;}Пишет this было 0x50
-
АвторСообщения
Просмотр 2 сообщений - с 1 по 2 (из 2 всего)
Для ответа в этой теме необходимо авторизоваться.