官术网_书友最值得收藏!

Common mistakes

Often, when using clocks, newbies to SFML tend to stick them in the wrong places and restart them at the wrong times. Things like that can result in "funky" behavior at best.

Note

Keep in mind that every line of code that isn't empty or commented out takes time to execute. Depending on how a function that is being called, or a class that is being constructed, is implemented, the time value might range from miniscule to infinite.

Things like updating all of the game entities in the world, performing calculations, and rendering are fairly computationally expensive, so make sure to not somehow exclude these calls from the span of your time measurement. Always make sure that restarting the clock and grabbing the elapsed time is the last thing you're doing before the main game loop ends.

Another mistake is having your clock object within the wrong scope. Consider this example:

void Game::SomeMethod(){
    sf::Clock clock;
    ...
    sf::Time time = clock.getElapsedTime();
}

Assuming that the intention of this code was to measure anything else other than the time since the sf::Clock object was initiated, this code will produce faulty results. Creating an instance of a clock simply measures the time it has been alive within its scope, not anything else. This is the reason why the clock in the game class was declared as the class member. Since the clock is created on the stack, as soon as the method above concludes, the clock will be destroyed again.

Keeping an elapsed time in a float data type, or any other data type that isn't sf::Time for that matter, is also something that's generally frowned upon. Something like this would not be a great example of proper use of SFML:

class Game{
...
private:
...
    float m_elapsed;
...
};

Although it works, this isn't exactly type-safe. It also requires more type conversions along the way, since you have to call one of the three conversion methods each time the clock gets restarted. One more nail to seal the coffin would be code readability. SFML provides its own time class for a reason and convenience, so unless there's a good reason not to use it, do avoid any other data types.

One last thing that deserves a mention since we're talking about time is the console output in C++. While it's just fine to print something out every now and then, even for just debugging purposes, constant console spam will slow your application down. The console output itself is quite slow and cannot be expected to execute at exactly the same speed as the rest of your program. Printing something on every iteration of the main game loop, for example, would throttle your application speed horribly.

主站蜘蛛池模板: 体育| 深圳市| 宁阳县| 景泰县| 蓬莱市| 镇远县| 澄城县| 徐水县| 新余市| 临潭县| 忻州市| 怀来县| 湟源县| 尉氏县| 拜泉县| 汝南县| 图木舒克市| 石家庄市| 花莲县| 类乌齐县| 陇南市| 栾川县| 华阴市| 礼泉县| 裕民县| 盐源县| 高邑县| 阳江市| 延边| 偏关县| 阿拉尔市| 吉隆县| 荆州市| 凤城市| 台前县| 屏东市| 徐水县| 湘潭县| 米泉市| 衢州市| 阳山县|