SFML и C++ Уроки \ Разработка игр › Форумы › SFML System, Window и другие вопросы › Игра змейка. Организация движения
В этой теме 6 ответов, 3 участника, последнее обновление sHistrila 8 года/лет, 6 мес. назад.
-
АвторСообщения
-
хочу сделать нормальное движение змейка, чтоб когда поворачивает голова, тело доходило до точки(где повернула голова) и только тогда начало поворачивать, а не одновременно с головой.
И вот еще, если моя змейка состоит из 3 частей: хвост-тело-голова, когда собираю еду тело на один увеличивалось
Спасибо)
вот код, он весь твой, ничего своего помимо текстур не добавлял
C++123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149#include<SFML/Graphics.hpp>#include<iostream>#include "map.h"using namespace sf;//включаем пространство имен sf, чтобы постоянно не писать sf::class Player { // класс Игрокаpublic:float x, y, w, h, dx, dy, speed;int dir;String File;Image image;Texture texture;Sprite sprite;Player(String F, float X, float Y, float W, float H){dir = 0; speed = 0;dx=0; dy=0;File = F;//имя файла+расширениеw = W; h = H;//высота и ширинаimage.loadFromFile("images/" + File);image.createMaskFromColor(Color(255, 0, 255));texture.loadFromImage(image);sprite.setTexture(texture);x = X; y = Y;sprite.setTextureRect(IntRect(0, 0, w, h));}void update(float time){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;y += dy*time;sprite.setPosition(x,y);}};int main(){RenderWindow window(sf::VideoMode(600, 400), "Lesson 3. kychka-pc.ru");Image map_image;map_image.loadFromFile("images/map.png");Texture map;map.loadFromImage(map_image);Sprite s_map;s_map.setTexture(map);Player g("golova.png", 0 , 200, 18.0, 18.0);Player t("telo.png",0 ,182 , 18.0, 18.0);Player x("xvost.png",0 ,164 , 18.0, 18.0);float CurrentFrame = 0;Clock clock;while (window.isOpen()){float time = clock.getElapsedTime().asMicroseconds();clock.restart();time = time/1000;sf::Event event;while (window.pollEvent(event)){if (event.type == sf::Event::Closed)window.close();}if ((Keyboard::isKeyPressed(Keyboard::Left))) {g.dir = 1; g.speed = 0.1;t.dir =1; g.speed = 0.1;x.dir =1 ; x.speed = 0.1;CurrentFrame += 0.005*time;g.sprite.setTextureRect(IntRect(18, 18, 18, 18));t.sprite.setTextureRect(IntRect(18, 18, 18, 18));x.sprite.setTextureRect(IntRect(18, 18, 18, 18));}if ((Keyboard::isKeyPressed(Keyboard::Right))) {for(int q=1; q>0; --q)g.dir = 0; g.speed = 0.1; //текстура головыt.dir = 0; t.speed = 0.1; //текстура телаx.dir =0 ; x.speed = 0.1; // текстура хвостаCurrentFrame += 0.005*time;g.sprite.setTextureRect(IntRect(0 , 18, 18, 18));t.sprite.setTextureRect(IntRect(0, 18, 18, 18));x.sprite.setTextureRect(IntRect(0, 18, 18, 18));}if ((Keyboard::isKeyPressed(Keyboard::Up))) {g.dir = 3; g.speed = 0.1;t.dir = 3; t.speed = 0.1;x.dir = 3; x.speed = 0.1;CurrentFrame += 0.005*time;g.sprite.setTextureRect(IntRect(18, 0, 18, 18));t.sprite.setTextureRect(IntRect(18, 0, 18, 18));x.sprite.setTextureRect(IntRect(18, 0,18, 18));}if ((Keyboard::isKeyPressed(Keyboard::Down))) {g.dir = 2; g.speed = 0.1;t.dir = 2; t.speed = 0.1;x.dir =2; x.speed = 0.1;CurrentFrame += 0.005*time;if (CurrentFrame > 3) CurrentFrame -= 3;g.sprite.setTextureRect(IntRect(0, 0, 18, 18));t.sprite.setTextureRect(IntRect(0, 0, 18, 18));x.sprite.setTextureRect(IntRect(0, 0, 18, 18));}g.update(time);t.update(time);x.update(time);window.clear();for (int i = 0; i < HEIGHT_MAP; i++)for (int j = 0; j < WIDTH_MAP; j++){if (TileMap[i][j] == ' ') s_map.setTextureRect(IntRect(0, 0, 20, 20));if (TileMap[i][j] == 's') s_map.setTextureRect(IntRect(20, 0, 20, 20 ));s_map.setPosition(j * 20, i * 20);window.draw(s_map);}window.draw(g.sprite);window.draw(t.sprite);window.draw(x.sprite);window.display();}return 0;}Вложения:
You must be logged in to view attached files.Тебе нужно динамически выделять новые объекты тела и двигать их циклом.
Запоминать координаты поворота и т.д.когда на opengl делал змейку, то создавал массив с координатами x y выглядело примерное так for (int i=kol;i>0;–i)
{z[i].x=z[i-1].x;
z[i].y=z[i-1].y;}, не понимая как такое можно здесь реализоватьмне переписывать class player или создать отдельный?
Ты сможешь создать массив объектов, если у тебя будет конструктор по умолчанию.
Player(){}Я скидывал вроде бы код змейки тебе, там алгоритм нужный тебе есть.
посмотри ещё тут
Спасибо большое)
-
АвторСообщения
Для ответа в этой теме необходимо авторизоваться.