SFML и C++ Уроки \ Разработка игр › Форумы › SFML Graphics › Ребят нужна помощь с анимацией › Ответ в теме: Ребят нужна помощь с анимацией
C++
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 |
#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; } |