Созданные ответы форума
-
АвторСообщения
-
*Headbang* Sprite::setTextureRect принимает в качестве аргумента IntRect который указывает с какого места текстуры нужно брать картинку.
Ну и мы же используем язык по большей части ориентированый на ООП, дак почему же нам не использовать это?C++123456789101112131415161718192021222324252627282930313233343536//AnimatedSprite.h/// \brief A sprite that can be animated by Animation objects.class AnimatedSprite : public sf::Sprite{public:/// \brief Default Constructor.AnimatedSprite();~AnimatedSprite();/// \brief Add an animation to the sprite.void addAnimation(const std::string& name, Animation animation);/// \brief Remove an animation.void removeAnimation(const std::string& name);/// \brief Play an animation. Optional looping parameter.void playAnimation(const std::string& name, bool loop = false);/// \brief Stops the currently running animation.void stopAnimation();/// \brief Returns true if a animation is currently being playedbool isAnimationPlaying();/// \brief Returns the name of the playing animationstd::string getCurrentAnimationName();/// \brief Updates the sprite. Should be called every frame./// or by param 's' you can getvoid update(sf::Time frameTime, int Frames = -1);private:std::map<std::string, Animation> animations;std::string currentAnimation;bool looping;};C++1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859//AnimatedSprite.cpp#include "AnimatedSprite.h"AnimatedSprite::AnimatedSprite() : looping(false), currentAnimation(""){//ctor}AnimatedSprite::~AnimatedSprite(){//dtor}void AnimatedSprite::addAnimation(const std::string& name, Animation animation){animations[name] = animation;}void AnimatedSprite::removeAnimation(const std::string& name){auto pos = animations.find(name);if(pos != animations.end())animations.erase(pos);}void AnimatedSprite::playAnimation(const std::string& name, bool loop){if(animations.find(name) != animations.end()){currentAnimation = name;looping = loop;}}void AnimatedSprite::stopAnimation(){currentAnimation = "";}bool AnimatedSprite::isAnimationPlaying(){return (!currentAnimation.empty());}std::string AnimatedSprite::getCurrentAnimationName(){return currentAnimation;}void AnimatedSprite::update(sf::Time frameTime,int Frame){if(!currentAnimation.empty()) //Are we actually running an animation?{if(!animations[currentAnimation].update(frameTime, Frame) && !looping) //If the animation is finished and we are not looping, stop the animation.currentAnimation = "";else //Else we just update our subrectsetTextureRect(animations[currentAnimation].getCurrentFrame());}}C++123456789101112131415161718192021222324252627282930313233343536373839404142434445464748//Animation.h#ifndef ANIMATION_H#define ANIMATION_H#include <SFML/System/Time.hpp>#include <SFML/Graphics/Rect.hpp>#include <vector>/// \brief A class that stores animation data.class Animation{friend class AnimatedSprite;public:/// \brief Constructor.Animation(sf::Time duration = sf::Time::Zero, bool Manual = false);~Animation();/// \brief Sets the duration of the animation.void setDuration(sf::Time duration);/// \brief Add a frame to the animation.////// A frame is actually just an IntRect object which specifies the subrectangle of the texture.void addFrame(sf::IntRect rect);/// \brief Add a siquence of frames to the animation.void addComplexyUpToDown(int frameCount, int W, int H, int xStart = 0, int yStart = 0);/// \brief Add a siquence of frames to the animation.void addComplexyLeftToRight(int frameCount, int W, int H, int xStart = 0, int yStart = 0);/// \brief Add a siquence of frames to the animation.void addComplexyRightToLeft(int frameCount, int W, int H, int xStart, int yStart);private:sf::IntRect getCurrentFrame();bool update(sf::Time frametime, int Frames = -1);void reset();bool manual;sf::Time duration;sf::Time passedTime;std::vector<sf::IntRect> frames;unsigned currentFrame;};#endif // ANIMATION_HC++123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899//Animation.cpp#include "Animation.h"Animation::Animation(sf::Time dur, bool Manual) : passedTime(sf::Time::Zero), currentFrame(0){duration = dur;manual = Manual;}Animation::~Animation(){//dtor}void Animation::setDuration(sf::Time dur){duration = dur;}bool Animation::update(sf::Time frametime, int Frames){passedTime += frametime;if (!manual && Frames < 0)currentFrame = std::floor((passedTime.asSeconds()/duration.asSeconds()) * (frames.size()-1) + 0.5);else if (Frames == -2){currentFrame++;if (currentFrame > frames.size()-1){currentFrame = 0;return false;}}else if (Frames == -3){currentFrame--;if (currentFrame < 0){currentFrame = frames.size()-1;return false;}}else if (Frames > -1){currentFrame = Frames;if (currentFrame > frames.size() - 1){reset();return false;}}if(passedTime > duration && !manual){reset();return false;}return true;}sf::IntRect Animation::getCurrentFrame(){return frames[currentFrame];}void Animation::addFrame(sf::IntRect rect){frames.push_back(rect);}void Animation::addComplexyLeftToRight(int frameCount, int W, int H,int xStart, int yStart){for (int i = 1; i < frameCount; i++){addFrame(sf::IntRect(xStart+(W*i-W),yStart,W,H));}}void Animation::addComplexyRightToLeft(int frameCount, int W, int H, int xStart, int yStart){for (int i = frameCount; i > 0; i--){addFrame(sf::IntRect(xStart + (W*i - W), yStart, W, H));}}void Animation::addComplexyUpToDown(int frameCount, int W, int H, int xStart, int yStart){for (int i = 1; i < frameCount; i++){addFrame(sf::IntRect(xStart, yStart + (H*i - H), W, H));}}void Animation::reset(){passedTime = sf::Time::Zero;}C++1234567891011121314151617//ПримерAnimatedSprite sprite = AnimatedSprite();sprite.setTexture(texture);//Подгружаем текстуру как к обычному спрайтуAnimation anim1 = Animation(sf::milliseconds(1200));//В параметре указываем длительность анимации, сейчас 1,2 секундыanim1.addComplexyLeftToRight(7, 32, 64, 0, 65);//Можно добавлять и по кадрам, но этот метод позволяет добавлять кадры если они стоят в ряд куда проще//1 аргумент количество кадров, 2 - длинна каждого кадра, 3 - высота, 4 и 5 это оффсеты на текстуре по X и Y соответственноsprite.addAnimation("anim1", anim1);//Передаём анимацию спрайту с заданым именем.sprite.playAnimation("anim1");//Запускаем анимацю с заданым именемClock clock;Time time = clock.restart();sprite.update(time);//Ну и каждый тик спрайт автоматически подгонит нужный кадр если ему передавать времяanarant75 занимаясь некропостингом никогда не жди что кто-то припрётся и ответит по данной теме
Каждый раз при запуске дебага в папке проэкта студя создаёт exe файл с названием проэкта в соответствующей папке
Origin это точка появления спрайта. Для анимации используется setTextureRect()
А цикл пула ивентов не выпадает из цикла?
while (window.poolEvent(event))Вобще: ты далеко не всё перерыл. Если окно просто встаёт в ступор при помощи дебага отлавливай где ты попадаешь в бесконечную рекурсию, цикл не имеющий выхода и прочие вещи которые не дают окну доходить до window.display(), либо в блок сокетом(Если зависает при инициализации сетевой игры). А исходники можно разложить на том же GitHub
C++123456789int main(){setlocale(LC_ALL,"Rus");/*...*/return 0;}Поищи в гугле. Я так и не взялся за sfml-network конкретно и перешёл на Lidgren.Network(C#).
Как писали на оф сайте SocketSelector может хранить только ссылки на сокеты. А вобще банально в частях кода где нужно отправить/принять информацию извне проходись циклом по всем сокетам в списке
Не используй конвертацию в std::string. Только sf::String поддерживает юникод
Обьявление же:
C++1234567std::map<int, std::map<int, sf::Vector2f>> сVertices;/**/сVertices[j][i] = Vector2(j * 32, i * 32);/**/Переписать его в Vector2f. Привычка с XNA уже выработалась…
И почему же вы не можете в цикле найти кординаты? Сектора у вас разбиты 32×32, сответственно когда вы попадает в случай ‘v’
C++1234567891011121314151617181920for (int i = 0; i < HEIGHT_MAP; i++)for (int j = 0; j < WIDTH_MAP; j++){Count = 0;switch (TileMap[i][j]){case '0': m.MapSr.setTextureRect(IntRect(64, 0, 32, 32)); break;case 'v':сVertices[j][i] = Vector2(j * 32, i * 32);/*x = j * 32;y = i * 32;*/break;case '-': m.MapSr.setTextureRect(IntRect(128, 0, 32, 32)); break;case '|': m.MapSr.setTextureRect(IntRect(96, 0, 32, 32)); break;default: m.MapSr.setTextureRect(IntRect(0, 0, 32, 32)); break;}m.MapSr.setPosition(j * 32, i * 32);window.draw(m.MapSr);}vproject57, Я не понимаю зачем ты так себе усложняешь жизнь. Просто сделай масив который будет содержть кординаты вершин в строке и после ввода пользователем данных просто через обращение к этому масиву находи нужные тебе строки и заменяй их.
У тебя обновление позиции спрайта находится в пуле ивентов. Попробуй начать вводить текст с клавиатуры и увидишь тот же эффект что и немного двигая мышь. Что бы пофиксить это логика перемещения спрайта должна быть вынесена в главный цикл, а не пул ивентов:
C++123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173while (window.isOpen()){float time = clock.getElapsedTime().asMicroseconds();clock.restart();time = time / 800;if (p.life) gameTime = gameTimeClock.getElapsedTime().asSeconds();else {view.rotate(0.1);view.zoom(1.0006f);}//else// view.move(0.1, 0); // движение камеры вправоVector2i pixelPos = Mouse::getPosition(window);//забираем коорд курсораVector2f pos = window.mapPixelToCoords(pixelPos);//переводим их в игровые (уходим от коорд окна)Event event;while (window.pollEvent(event)){if (event.type == Event::Closed)window.close();if (event.type == Event::MouseButtonPressed)//если нажата клавиша мышиif (event.key.code == Mouse::Left) {//а именно леваяif (p.sprite.getGlobalBounds().contains(pos.x, pos.y))//и при этом координата курсора попадает в спрайт{p.sprite.setColor(Color::Green);//красим спрайт в зеленый,тем самым говоря игроку,что он выбрал персонажа и может сделать ходp.isSelect = true;}}if (p.isSelect)//если выбрали объектif (event.type == Event::MouseButtonPressed)//если нажата клавиша мышиif (event.key.code == Mouse::Right) {//а именно праваяp.isMove = true;//то начинаем движениеp.isSelect = false;//объект уже не выбранp.sprite.setColor(Color::White);//возвращаем обычный цвет спрайтуtempX = pos.x;//забираем координату нажатия курсора ХtempY = pos.y;//и Y}////////////////////////////////////////////////if (p.isMove) {//distance = sqrt((tempX - p.x)*(tempX - p.x) + (tempY - p.y)*(tempY - p.y));//считаем дистанцию (длину от точки А до точки Б). формула длины вектора//if (distance > 2) {//этим условием убираем дергание во время конечной позиции спрайта// p.x += 0.1*time*(tempX - p.x) / distance;//идем по иксу с помощью вектора нормали// p.y += 0.1*time*(tempY - p.y) / distance;//идем по игреку так же//}//else// p.isMove = false;//}if(event.type == Event::KeyPressed)if (event.key.code == Keyboard::Tab) {switch (showMissionText) {case true: {std::ostringstream playerHealthString;playerHealthString << p.health;std::ostringstream task;task << getTextMission(getCurrentMission(p.getplayercoordinateX()));text2.setString("Здоровье: " + playerHealthString.str() + "\n" + task.str() + "\n");showMissionText = false;break;}case false: {/*text2.setString(" ");*/showMissionText = true;break;}}}}if (p.life) {if (Keyboard::isKeyPressed(Keyboard::Left)) {p.dir = 1; p.speed = 0.1;CurrentFrame += 0.005 * time;if (CurrentFrame > 2) CurrentFrame -= 2;p.sprite.setTextureRect(IntRect(46 * int(CurrentFrame), 0, 46, 45));}if (Keyboard::isKeyPressed(Keyboard::Right)) {p.dir = 0; p.speed = 0.1;CurrentFrame += 0.005 * time;if (CurrentFrame > 2) CurrentFrame -= 2;p.sprite.setTextureRect(IntRect(46 * int(CurrentFrame) + 46, 0, -46, 45));}if (Keyboard::isKeyPressed(Keyboard::Up)) {p.dir = 3; p.speed = 0.1;CurrentFrame += 0.005 * time;if (CurrentFrame > 2) CurrentFrame -= 2;p.sprite.setTextureRect(IntRect(46 * int(CurrentFrame) + 46, 0, -46, 45));}if (Keyboard::isKeyPressed(Keyboard::Down)) {p.dir = 2; p.speed = 0.1;CurrentFrame += 0.005 * time;if (CurrentFrame > 2) CurrentFrame -= 2;p.sprite.setTextureRect(IntRect(46 * int(CurrentFrame) + 46, 0, -46, 45));}getplayercoordinateforview(p.getplayercoordinateX(), p.getplayercoordinateY());}// КАМЕРА ДЛЯ СТРАТЕГИИ//Vector2i localPosition = Mouse::getPosition(window);//if (localPosition.x < 3) { view.move(-0.2*time, 0); }//если пришли курсором в левый край экрана,то двигаем камеру влево//if (localPosition.x > window.getSize().x - 3) { view.move(0.2*time, 0); }//правый край-вправо//if (localPosition.y > window.getSize().y - 3) { view.move(0, 0.2*time); }//нижний край - вниз//if (localPosition.y < 3) { view.move(0, -0.2*time); }//верхний край - вверхif (p.isMove) {//Перемещён сюдаdistance = sqrt((tempX - p.x)*(tempX - p.x) + (tempY - p.y)*(tempY - p.y));//считаем дистанцию (длину от точки А до точки Б). формула длины вектораif (distance > 2) {//этим условием убираем дергание во время конечной позиции спрайтаp.x += 0.1*time*(tempX - p.x) / distance;//идем по иксу с помощью вектора нормалиp.y += 0.1*time*(tempY - p.y) / distance;//идем по игреку так же}elsep.isMove = false;}p.update(time);window.setView(view);window.clear(Color(195,151,78));//--------------------------------------------------------------------------------------------------------for (int i = 0; i < HEIGHT_MAP; i++)for (int j = 0; j < WIDTH_MAP; j++){if (TileMap[i][j] == ' ') s_map.setTextureRect(IntRect(65, 0, 65, 65));if (TileMap[i][j] == 's') s_map.setTextureRect(IntRect(130, 0, 65, 65));if ((TileMap[i][j] == '0')) s_map.setTextureRect(IntRect(0, 0, 65, 65));if ((TileMap[i][j] == 'f')) s_map.setTextureRect(IntRect(195, 0, 65, 65));if ((TileMap[i][j] == 'h')) s_map.setTextureRect(IntRect(260, 0, 65, 65));s_map.setPosition(j * 65, i * 65);//по сути раскидывает квадратики, превращая в карту. то есть задает каждому из них позицию. если убрать, то вся карта нарисуется в одном квадрате 65*65 и мы увидим один квадратwindow.draw(s_map);}//-----------------------------------------------------------------------------------------std::ostringstream playerScoreString, playerHealthString, gameTimeString;playerScoreString << p.playerScore;playerHealthString << p.health;gameTimeString << gameTime;text.setString("Собрано червячков:" + playerScoreString.str() + "\nЗдоровье: " + playerHealthString.str() + "\nВремя в игре: " + gameTimeString.str());text.setPosition(view.getCenter().x - 370, view.getCenter().y - 200);if (!showMissionText) {text2.setPosition(view.getCenter().x + 125, view.getCenter().y - 130);s_quest.setPosition(view.getCenter().x + 115, view.getCenter().y - 130);window.draw(s_quest);window.draw(text2); //Рисуем текст 2 (миссия)}window.draw(text);window.draw(p.sprite);window.display();} -
АвторСообщения