SFML实现60fps蛇形游戏:身体段移动重叠问题求助
SFML蛇形游戏60fps下蛇身重叠错位问题求助
我正在用C++ SFML实现一款简易蛇形游戏,遇到以下问题:
- 此前设置帧率15fps、每次移动20px时,游戏运行正常
- 切换到60fps后,尝试每4帧更新一次身体段的移动方向,导致蛇身出现重叠、错位的混乱状态
以下是我的实现代码及当前蛇身效果截图,恳请提供解决建议。
蛇类定义
class Snake{ public: Snake(); void drawSnake(sf::RenderWindow &window); void moveSnake(); void incrementSize(); sf::FloatRect snakePos(); //global bounds of snake private: sf::RectangleShape snake; std::vector<sf::RectangleShape> body; sf::Vector2f direction; std::vector<sf::Vector2f> segmentDirections; //this stores information for the velocity of each node in the snake int frames; float velocity = 5.f; int length; };
成员函数实现
Snake::Snake() : length(1), direction(5,0){ sf::RectangleShape segment(sf::Vector2f(20,20)); segment.setPosition(sf::Vector2f(20,20)); segment.setFillColor(sf::Color::White); body.push_back(segment); segmentDirections.push_back(direction); } void Snake::drawSnake(sf::RenderWindow &window){ for(sf::RectangleShape& seg : body){ window.draw(seg); } } void Snake::moveSnake(){ frames++; body[0].move(direction); // Update direction of the head based on user input if(sf::Keyboard::isKeyPressed(sf::Keyboard::A) || sf::Keyboard::isKeyPressed(sf::Keyboard::Left)){ direction = sf::Vector2f(-velocity,0); } if(sf::Keyboard::isKeyPressed(sf::Keyboard::S) || sf::Keyboard::isKeyPressed(sf::Keyboard::Down)){ direction = sf::Vector2f(0,velocity); } if(sf::Keyboard::isKeyPressed(sf::Keyboard::D) || sf::Keyboard::isKeyPressed(sf::Keyboard::Right)){ direction = sf::Vector2f(velocity,0); } if(sf::Keyboard::isKeyPressed(sf::Keyboard::W) || sf::Keyboard::isKeyPressed(sf::Keyboard::Up)){ direction = sf::Vector2f(0,-velocity); } segmentDirections[0] = direction; if(frames % 4 == 0){ for(int i = segmentDirections.size() - 1; i > 0; --i){ segmentDirections[i] = segmentDirections[i-1]; } frames = 0; } for(int i = 1; i < body.size(); i++){ body[i].move(segmentDirections[i]); } } void Snake::incrementSize(){ sf::RectangleShape segment(sf::Vector2f(20,20)); segment.setFillColor(sf::Color::White); segment = body.back(); segmentDirections.push_back(direction); body.push_back(segment); } sf::FloatRect Snake::snakePos(){ return body[0].getGlobalBounds(); }
当前蛇身效果

内容的提问来源于stack exchange,提问作者stubbie
相关产品推荐
相关产品推荐

