SFML и C++ Уроки \ Разработка игр › Форумы › SFML System, Window и другие вопросы › Проблемы с обработкой столкновений с объектами при использовании tinyXML(урок22) › Ответ в теме: Проблемы с обработкой столкновений с объектами при использовании tinyXML(урок22)
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 240 |
#include <vector> #include <map> #include <SFML/Graphics.hpp> #include <sstream> #include "map.h" #include "view.h" #include "iostream" #include "level.h" #include <list> #include <vector> using namespace sf; using namespace std; RectangleShape Rectangle(Vector2f(32, 32)); class Entity { public: vector<Object>obj; float dx, dy, x, y, speed, moveTimer; float CurrentFrame = 0; int w, h, health; bool life, isMove; 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 = 15; dx = 0; dy = 0; life = true; 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, stay } state; Player(Image &image, String Name, Level&lev, float X, float Y, int W, int H) :Entity(image, Name, X, Y, W, H) { state = stay; sprite.setTextureRect(IntRect(0, 0, w, h)); obj = lev.GetAllObjects(); } void update(float time) { if(life)control(time); switch (state) { case right:dx = speed; dy = 0; break; case left:dx = -speed; dy = 0; break; case up:dx = 0; dy = -speed; break; case down:dx = 0; dy = speed; break; case stay: break; } x += dx*time; checkCollisionWithMap(dx, 0); y += dy*time; checkCollisionWithMap(0, dy); if (!isMove)speed = 0; sprite.setPosition(x , y ); if (health <= 0){ life = false; } if (life){ getplayercoordinateforview(x, y); } } void control(float time) { if (Keyboard::isKeyPressed(Keyboard::Left)) { state = left; speed = 0.1; sprite.setTextureRect(IntRect(32 * int(CurrentFrame), 32, 32, 32)); CurrentFrame += 0.005*time; if (CurrentFrame > 3)CurrentFrame -= 3; exit; } else if (Keyboard::isKeyPressed(Keyboard::Right)) { state = right; speed = 0.1; sprite.setTextureRect(IntRect(32 * int(CurrentFrame), 64, 32, 32)); CurrentFrame += 0.005*time; if (CurrentFrame > 3)CurrentFrame -= 3; exit; } else if (Keyboard::isKeyPressed(Keyboard::Up)) { state = up; speed = 0.1; sprite.setTextureRect(IntRect(32 * int(CurrentFrame), 96, 32, 32)); CurrentFrame += 0.005*time; if (CurrentFrame > 3)CurrentFrame -= 3; exit; } else if (Keyboard::isKeyPressed(Keyboard::Down)) { state = down; speed = 0.1; sprite.setTextureRect(IntRect(32 * int(CurrentFrame), 0, 32, 32)); CurrentFrame += 0.005*time; if (CurrentFrame > 3)CurrentFrame -= 3; exit; } } 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") { cout << h<<" "<<w<<"/n"; if (Dy>0) { y = obj[i].rect.top - h; dy = 0; } 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; } if (Dx<0) { x = obj[i].rect.left + obj[i].rect.width; dx = 0; } } } } float getplayercoordinateX(){ return x; } float getplayercoordinateY(){ return 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"); sprite.setTextureRect(IntRect(0, 0, w, h)); dx = 0.05;//даем скорость.этот объект всегда двигается } void checkCollisionWithMap(float Dx, float Dy, float time) { 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; } 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) { moveTimer += time; if (moveTimer>3000){ sprite.scale(-1, 1); dx *= -1; moveTimer = 0; } sprite.setTextureRect(IntRect(32 * int(CurrentFrame), 64, 32, 32)); CurrentFrame += 0.005*time; if (CurrentFrame > 3)CurrentFrame -= 3; checkCollisionWithMap(dx, 0, time); if(life)x += dx*time; sprite.setPosition(x , y); if (health <= 0){ life = false; } } }; int main() { char num = '0'; Font font; font.loadFromFile("ALGER.ttf"); Text text("", font, 20); text.setColor(Color::Red); RenderWindow window(sf::VideoMode(800, 600), "Dungeon test"); view.reset(FloatRect(0, 0, 800, 600)); Level lvl; lvl.LoadFromFile("map.tmx"); Image map_image; map_image.loadFromFile("images/maps.png"); Texture map; map.loadFromImage(map_image); Sprite s_map; s_map.setTexture(map); Image Bobimage; Bobimage.loadFromFile("Images/testhero.png"); Image Lol; Lol.loadFromFile("Images/testhero.png"); Object player = lvl.GetObject("player"); Object LalkaObject = lvl.GetObject("Lalka"); Player Bob(Bobimage, "Player", lvl, player.rect.left, player.rect.top, 11, 6); Enemy Lalka(Lol, "Lalka", lvl, LalkaObject.rect.left, LalkaObject.rect.top, 6, 6); text.setPosition(view.getCenter().x - 165, view.getCenter().y - 200);//задаем позицию текста, отступая от центра камеры float CurrentFrame = 0; Clock clock; while (window.isOpen()) { ostringstream PlayerHealthString; PlayerHealthString << Bob.health; text.setString("Health:" + PlayerHealthString.str());//задаем строку тексту и вызываем сформированную выше строку методом .str() window.draw(text);//рисую этот текст float time = clock.getElapsedTime().asMicroseconds(); clock.restart(); time = time / 700; Event event; while (window.pollEvent(event)) { if (event.type == Event::Closed) window.close(); } ////////////////////////Controlings with animations////////////////////////// Bob.update(time); Lalka.update(time); window.setView(view); window.clear(); lvl.Draw(window); ///////////Map drawing////////// text.setPosition(view.getCenter().x + 230, view.getCenter().y + -300); window.draw(Bob.sprite); window.draw(Lalka.sprite); window.draw(text); window.display(); } return 0; } |
Ладно, вопрос решил) протупил в одном моменте
Только осталась одна проблема – если сверху подходить к объекту, он наполовину на него заезжает, а с других сторон – нет.(игра с видом сверху)
Прикрепляю весь main.cpp
Буду премного признателен, если мне укажут на мою ошибку