Созданные ответы форума
Просмотр 1 сообщения - с 1 по 1 (всего 1)
-
АвторСообщения
-
C++123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239#include <SFML/Graphics.hpp>#include "view.h"#include <iostream>#include <sstream>#include "mission.h"#include "iostream"#include "level.h"#include <vector>#include <list>using namespace sf;////////////////////////////////////Общий класс-родитель//////////////////////////class Entity {public:std::vector<Object> obj;//вектор объектов картыfloat dx, dy, x, y, speed,moveTimer;float currentFrame = 0;int w,h,health;int dir;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;dir = 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, up, down, jump, stay } state;int playerScore;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(4, 19, w, h));}}void control(){if (Keyboard::isKeyPressed(Keyboard::Left)) {state = left; speed = 0.1;}if (Keyboard::isKeyPressed(Keyboard::Right)) {state = right; speed = 0.1;}if ((Keyboard::isKeyPressed(Keyboard::Up)) && (onGround)) {state = jump; dy = -0.6; onGround = false;}if (Keyboard::isKeyPressed(Keyboard::Down)) {state = down;}}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; }}}}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 stay: break;}switch (dir){case 0: dx = speed; dy = 0; break;case 1: dx = -speed; dy = 0; break;case 2: dx = 0; dy = speed; break;case 3: dx = 0; dy = -speed; break;}x += dx*time;checkCollisionWithMap(dx, 0);y += dy*time;checkCollisionWithMap(0, dy);sprite.setPosition(x + w / 2, y + h / 2);if (health <= 0){ life = false; }if (!isMove){ speed = 0; }setPlayerCoordinateForView(x, y);if (life) { setPlayerCoordinateForView(x, y); }dy = dy + 0.0015*time;}};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"){//если встретили препятствие (объект с именем 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); }//}}}void update(float time){if (name == "EasyEnemy"){//moveTimer += time;if (moveTimer>3000){ dx *= -1; moveTimer = 0; }//меняет направление примерно каждые 3 секcheckCollisionWithMap(dx, 0);x += dx*time;sprite.setPosition(x + w / 2, y + h / 2);if (health <= 0){ life = false; }}}};int main(){RenderWindow window(VideoMode(640, 480), "Lesson 22. kychka-pc.ru");view.reset(FloatRect(0, 0, 640, 480));Level lvl;//создали экземпляр класса уровеньlvl.LoadFromFile("map.tmx");//загрузили в него карту, внутри класса с помощью методов он ее обработает.Image heroImage;heroImage.loadFromFile("images/Hero.png");Image easyEnemyImage;easyEnemyImage.loadFromFile("images/shamaich.png");easyEnemyImage.createMaskFromColor(Color(255, 0, 0));Object player=lvl.GetObject("player");//объект игрока на нашей карте.задаем координаты игроку в начале при помощи негоObject easyEnemyObject = lvl.GetObject("easyEnemy");//объект легкого врага на нашей карте.задаем координаты игроку в начале при помощи него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;float currentFrame = 0;while (window.isOpen()){float time = clock.getElapsedTime().asMicroseconds();clock.restart();time = time / 800;Event event;while (window.pollEvent(event)){if (event.type == sf::Event::Closed)window.close();if (p.life) {if (Keyboard::isKeyPressed(Keyboard::Left)) {p.dir = 1;currentFrame += 0.05*time;if (currentFrame > 3) currentFrame -= 3;p.sprite.setTextureRect(IntRect(96 * int(currentFrame), 96, 96, 96));}if (Keyboard::isKeyPressed(Keyboard::Right)) {p.dir = 0;currentFrame += 0.05*time;if (currentFrame > 3) currentFrame -= 3;p.sprite.setTextureRect(IntRect(96 * int(currentFrame), 192, 96, 96));}if (Keyboard::isKeyPressed(Keyboard::Up)) {p.dir = 3;currentFrame += 0.05*time;if (currentFrame > 3) currentFrame -= 3;p.sprite.setTextureRect(IntRect(96 * int(currentFrame), 307, 96, 96));}if (Keyboard::isKeyPressed(Keyboard::Down)) {p.dir = 2;currentFrame += 0.05*time;if (currentFrame > 3) currentFrame -= 3;p.sprite.setTextureRect(IntRect(96 * int(currentFrame), 0, 96, 96));}}}p.update(time);easyEnemy.update(time);window.setView(view);window.clear(Color(77,83,140));lvl.Draw(window);//рисуем новую картуwindow.draw(easyEnemy.sprite);window.draw(p.sprite);window.display();}return 0;}
-
АвторСообщения
Просмотр 1 сообщения - с 1 по 1 (всего 1)