【发布时间】:2016-05-13 11:36:05
【问题描述】:
我用 C++ 和 SFML 编写了一个简单的程序。我的问题是当我移动我的精灵时它非常不稳定。我的精灵会移动一点,然后加速到平稳的移动,直到我按下另一个键,它会再次停止然后继续。我希望这是有道理的,但简而言之,我只是希望我的精灵运动更平滑。我的代码:
#include <SFML/Graphics.hpp>
#include <math.h>
#include <iostream>
int main()
{
float x = 0;
float y = 0;
sf::Vector2f position;
sf::Vector2f velocity;
float maxspeed = 3.0f;
float accel = 1.0f;
float decel = 0.02f;
sf::RenderWindow window(sf::VideoMode(400, 400), "SFML works!");
sf::Texture tplayer;
if (!tplayer.loadFromFile("character.png"))
{
// error...
}
sf::Sprite splayer;
splayer.setTexture(tplayer);
splayer.setOrigin(sf::Vector2f(0, 0));
splayer.setTextureRect(sf::IntRect(0, 0, 16, 38));
sf::Vector2f pos = splayer.getPosition();
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
velocity.x -= accel;
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
velocity.x += accel;
else
velocity.x *= decel;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
velocity.y -= accel;
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
velocity.y += accel;
else
velocity.y *= decel;
if (velocity.x < -maxspeed) velocity.x = -maxspeed;
if (velocity.x > maxspeed) velocity.x = maxspeed;
if (velocity.y < -maxspeed) velocity.y = -maxspeed;
if (velocity.y > maxspeed) velocity.y = maxspeed;
position += velocity;
splayer.setPosition(position);
}
}
window.clear();
window.draw(splayer);
window.display();
window.setFramerateLimit(60);
}
return 0;
}
【问题讨论】:
标签: c++ animation sprite codeblocks sfml