SFML и C++ Уроки \ Разработка игр › Форумы › Логика игр › Стрельба по клику мыши › Ответ в теме: Стрельба по клику мыши
Все равно не могу разобраться
Как сюда добавить выстрел? Пробовал сделать как вы написали, ничего не получилось (не достаточно опыта и знаний, только начал). Так же пока не делал общий класс Entities.
Суть понятна, но как реализовать нет.
Вот мой код:
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 241 242 243 244 245 246 247 248 249 250 |
#include <SFML/Graphics.hpp> #include <iostream> #include <sstream> using namespace sf; using namespace std; const int level_max = 20; //Максимальный уровень персонажа class projectiles { public: float speed_projectiles = 3; float distance; Texture texture_projectiles; Sprite sprite_projectiles; Vector2i size_projectiles; //Размер спрайта Vector2f temp; Vector2f player; projectiles(Image &image, int size_projectiles_x, int size_projectiles_y, float tempX, float tempY, float player_x, float player_y) { texture_projectiles.loadFromImage(image); sprite_projectiles.setTexture(texture_projectiles); player.x = player_x; player.y = player_y; temp.x = tempX; temp.y = tempY; } }; class player{ public: float x, y; //Координаты персонажа float speed; //Скорость персонажа float CurrentFrame = 0; //Счетчик анимации персонажа int walk; //Направление персонажа int origin_player_y_for_wakl = 0; //Для правильной остановки персонажа (спрайта) int health_max = 100; //Максимальное здоровье float health = health_max; //Здоровье int level; //Уровень const int level_exp[level_max - 2] = {5, 10, 20, 40, 80, 160, 320, 640, 1280, 2560, 5120, 10240, 20480, 40960, 81920, 163840, 327680, 655360}; //Массив опыта int level_number = 0; //Счетчик массива опыта int level_experience; //Опыт игрока int level_check = level_exp[0]; //Для проверки опыта int free_point = 10; //Очки характеристик bool life; //Состояние (жив/мертв) Texture texture; Sprite sprite; Vector2i size_player; //Размер спрайта Vector2i origin_player; //Начало отрисовки спрайта string name_player; //Ник персонажа player(Image &image, String name, int size_player_x, int size_player_y, int origin_player_x, int origin_player_y, float position_x, float position_y) { texture.loadFromImage(image); sprite.setTexture(texture); name_player = name; x = position_x; y = position_y; size_player.x = size_player_x; size_player.y = size_player_y; origin_player.x = origin_player_x; origin_player.y = origin_player_y; sprite.setTextureRect(IntRect(origin_player.x, origin_player.y, size_player.x, size_player.y)); sprite.setPosition(x, y); //Координаты появления life = true; //Состояние: жив speed = 0.1; //Начальная скорость: 0.1 level_experience = 0; //Начальное кол-во опыта: 0 level = 1; //Начальный уровень: 1 } void control(float time) { if (!walk) //Для правильной остановки персонажа (спрайта) { if (origin_player_y_for_wakl == 0) sprite.setTextureRect(IntRect(origin_player.x, 0, size_player.x, size_player.y)); if (origin_player_y_for_wakl == size_player.y) sprite.setTextureRect(IntRect(origin_player.x, size_player.y * 1, size_player.x, size_player.y)); if (origin_player_y_for_wakl == size_player.y * 2) sprite.setTextureRect(IntRect(origin_player.x, size_player.y * 2, size_player.x, size_player.y)); if (origin_player_y_for_wakl == size_player.y * 3) sprite.setTextureRect(IntRect(origin_player.x, size_player.y * 3, size_player.x, size_player.y)); } if (Keyboard::isKeyPressed(Keyboard::A)) { walk = 1; origin_player_y_for_wakl = origin_player.y + size_player.y; sprite.setTextureRect(IntRect(origin_player.x + size_player.x * (int)CurrentFrame, origin_player_y_for_wakl, size_player.x, size_player.y)); } if (Keyboard::isKeyPressed(Keyboard::D)) { walk = 2; origin_player_y_for_wakl = origin_player.y + size_player.y * 2; sprite.setTextureRect(IntRect(origin_player.x + size_player.x * (int)CurrentFrame, origin_player_y_for_wakl, size_player.x, size_player.y)); } if (Keyboard::isKeyPressed(Keyboard::W)) { walk = 3; origin_player_y_for_wakl = origin_player.y + size_player.y * 3; sprite.setTextureRect(IntRect(origin_player.x + size_player.x * (int)CurrentFrame, origin_player_y_for_wakl, size_player.x, size_player.y)); } if (Keyboard::isKeyPressed(Keyboard::S)) { walk = 4; origin_player_y_for_wakl = origin_player.y; sprite.setTextureRect(IntRect(origin_player.x + size_player.x * (int)CurrentFrame, origin_player_y_for_wakl, size_player.x, size_player.y)); } if (Keyboard::isKeyPressed(Keyboard::A) & Keyboard::isKeyPressed(Keyboard::W)) { walk = 5; origin_player_y_for_wakl = origin_player.y + size_player.y * 3; sprite.setTextureRect(IntRect(origin_player.x + size_player.x * (int)CurrentFrame, origin_player_y_for_wakl, size_player.x, size_player.y)); } if (Keyboard::isKeyPressed(Keyboard::A) & Keyboard::isKeyPressed(Keyboard::S)) { walk = 6; origin_player_y_for_wakl = origin_player.y; sprite.setTextureRect(IntRect(origin_player.x + size_player.x * (int)CurrentFrame, origin_player_y_for_wakl, size_player.x, size_player.y)); } if (Keyboard::isKeyPressed(Keyboard::D) & Keyboard::isKeyPressed(Keyboard::S)) { walk = 7; origin_player_y_for_wakl = origin_player.y; sprite.setTextureRect(IntRect(origin_player.x + size_player.x * (int)CurrentFrame, origin_player_y_for_wakl, size_player.x, size_player.y)); } if (Keyboard::isKeyPressed(Keyboard::D) & Keyboard::isKeyPressed(Keyboard::W)) { walk = 8; origin_player_y_for_wakl = origin_player.y + size_player.y * 3; sprite.setTextureRect(IntRect(origin_player.x + size_player.x * (int)CurrentFrame, origin_player_y_for_wakl, size_player.x, size_player.y)); } if (Keyboard::isKeyPressed(Keyboard::Up)) health -= 1; //Уменьшаем ХП стрелкой вверх if (Keyboard::isKeyPressed(Keyboard::Right)) level_experience += 1000; //Добавляет опыт стрелкой вправо(+1000) if (Keyboard::isKeyPressed(Keyboard::Left)) level_experience += 10000; //Добавляет опыт стрелкой влево(+10000) if (walk) //Анимация движения { CurrentFrame += 0.005*time; if (CurrentFrame > 3) CurrentFrame -= 3; } switch (walk) { case 1: x -= speed*time; break; //Лево case 2: x += speed*time; break; //Право case 3: y -= speed*time; break; //Верх case 4: y += speed*time; break; //Низ case 5: x -= speed*time, y -= speed*time; break; //Лево-Верх case 6: x -= speed*time, y += speed*time; break; //Лево-Низ case 7: x += speed*time, y += speed*time; break; //Право-Низ case 8: x += speed*time, y -= speed*time; break; //Право-Верх } walk = 0; //Останавливаем персонажа sprite.setPosition(x, y); //Меняем координаты персонажа } void level_player() { if (level_experience >= level_check) //Проверка опыта / уровня { level_check += level_exp[level_number]; level_number++; //Переход на след. эл. массива опыта level++; //Повышаем уровень free_point += 2; //Добавляем 2 очка характеристик health_max += 20; health = health_max; //Восстанавливаем ХП } if (level == level_max) level_experience = 0; //Не даем прокачивать больше макс. уровня } void update(float time) { if (health < 1) life = false; //Здоровье ноль или меньше - мертв if (health > health_max) health = health_max; //Если ХП больше чем нужно if (life) control(time); //Подключаем управление if (life & health < health_max) health += 0.0004 * time; //Востановление ХП с течением времени level_player(); //Подключаем опыт и уровень } }; int main() { RenderWindow window; Vector2i position_window = window.getPosition(); window.create(VideoMode(800, 600), "Game"); window.setFramerateLimit(60); //FPS RectangleShape rectangle_tab(sf::Vector2f(230, 580)); //Окно информации на "Tab" rectangle_tab.setFillColor(sf::Color(0, 0, 0, 128)); //Черный цвет с прозрачностью rectangle_tab.setPosition(position_window.y + 10, position_window.x + 10); Clock clock; //Время Image image_player; //Игрок image_player.loadFromFile("images/sprite1.png"); image_player.createMaskFromColor(Color::White); // Цвет прозрачности Image image_projectiles; //Выстрел image_projectiles.loadFromFile("images/shoot.png"); image_projectiles.createMaskFromColor(Color::White); // Цвет прозрачности Font font; //Текст Text text_stats("", font, 14); font.loadFromFile("fonts/font_SEVENET_7_CYR.ttf"); text_stats.setColor(Color::White); // Объект класса player player p(image_player, "Player", 48, 48, 0, 0, 300, 400); /* 1. Image - Изображение 2. Name - Имя игрока 3. size_player_x - Размер по Х 4. size_player_y - Размер по Y 5. origin_player_x - Начало первого спрайта по Х 6. origin_player_y - Начало первого спрайта по Y 7. position_x - Начальная позиция спрайта по Y 8. position_y - Начальная позиция спрайта по Y */ while (window.isOpen()) { float time = clock.getElapsedTime().asMicroseconds(); clock.restart(); time = time / 800; Event event; while (window.pollEvent(event)) { if (event.type == Event::Closed) window.close(); } p.update(time); //Обновляем класс player с течением времени if (event.type == Event::MouseButtonPressed) //Нажата клавиша мыши if (event.key.code == Mouse::Left) //Левая { } window.clear(Color(128, 128, 128)); //Серый фон игры window.draw(p.sprite); //Рисуем персонажа if (Keyboard::isKeyPressed(Keyboard::Tab)) //Окно информации на "Tab" { ostringstream name_player; name_player << p.name_player; //Имя персонажа ostringstream health_player; health_player << (int)p.health; //Здоровье персонажа ostringstream level_player; level_player << p.level; //Уровень персонажа ostringstream exp_player; exp_player << p.level_experience; //Опыт персонажа ostringstream position_player_x; position_player_x << (int)p.x; //Координата X ostringstream position_player_y; position_player_y << (int)p.y; //Координата Y ostringstream free_point_player; free_point_player << p.free_point; //Доступные очки характеристик text_stats.setString("Имя: " + name_player.str() + "\n\nЗдоровье: " + health_player.str() + "\n\nУровень: " + level_player.str() + "\nОпыт: " + exp_player.str() + "\n\nКоординаты:\nX: " + position_player_x.str() + "\nY: " + position_player_y.str() + "\n\nОчки характеристик: " + free_point_player.str()); text_stats.setPosition(position_window.y + 20, position_window.x + 20); window.draw(rectangle_tab); //Выводим окно при нажатии "Tab" window.draw(text_stats); //Выводим текст при нажатии "Tab" } window.display(); } return 0; } |