Velocity and Time Elapsed in sfml 2.0

So I have been looking for hours now and I can't seem to find anything to help me with this, so I'll start by saying I am new, like very new, but I do understand that in order to have constant move speed at varying framerates I need to incorporate velocity and determine the time elapsed since the last iteration of the loop.

So this is what I have so far

#include <SFML/Graphics.hpp>

int main()
{
sf::RenderWindow window(sf::VideoMode(800, 600, 32), "Oliver Rules!");

float speed = 20.f;
float locX = 0.f;
float locY = 0.f;

sf::CircleShape circleOne(50);
circleOne.setFillColor(sf::Color(200, 40, 200));

sf::Clock clock;


while (window.isOpen())
{
    sf::Event event;
    while (window.pollEvent(event))
    {
        if (event.type == sf::Event::Closed)
            window.close();
    }



    sf::Time elapsed1 = clock.restart();

    if(sf::Keyboard::isKeyPressed(sf::Keyboard::A))
        {
            locX -= speed * elapsed1;
        }
    if(sf::Keyboard::isKeyPressed(sf::Keyboard::D))
        {
            locX += 0.1;
        }
    if(sf::Keyboard::isKeyPressed(sf::Keyboard::W))
        {
            locY -= 0.1;
        }
    if(sf::Keyboard::isKeyPressed(sf::Keyboard::S))
        {
            locY += 0.1;
        }


    circleOne.setPosition(locX, locY);
    circleOne.move(locX, locY);


    window.clear();
    window.draw(circleOne);
    window.display();
}

return 0;
}

What my problem is, is that I can not add or subtract from the variables I have initiated to be the location of my circleOne can not be edited due to the elapsed1 being a float I believe, so my question is, how do I get this to work?

Answers


Your problem is that speed and elapsed1 are not the same type. One is float while the other is sf::Time. If you want locX -= speed * elapsed1 to work, you will have to transform elapsed1 to float.

In order to do that, you can used the methods elapsed1.asSeconds, elapsed1.asMilliseconds and elapsed1.asMicroseconds, depending on the kind of units you want.

If you want to know more about that, you should have a look at the SFML 2.0 documentation for sf::Time.


Need Your Help


About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.