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

git(hub) remove commit from a merge

git merge commit rebase

My question in similar to git remove commit from a merge but I can't follow instructions suggested there, since my repository's history is a little bit different.

Are php resources passed by reference?

php parameter-passing

I discovered today that in addition to objects and primitives, PHP has resources. The documentation states that by default php passes names by value. But we know that in PHP 5, objects are referenc...

location based process in iphone sdk?

iphone ipad

I want to do local push Notification (giving alert) when the user comes in particular locations(in range).is it possible to do it? any example and tutorial please?