2.1 Time Processing

  • Tutorial


From a translator: This article is the sixth in the translation cycle of the official SFML library guide. A past article can be found here. This series of articles aims to provide people who do not know the original language with the opportunity to familiarize themselves with this library. SFML is a simple and cross-platform multimedia library. SFML provides a simple interface for developing games and other multimedia applications. The original article can be found here . Let's get started.

Table of contents:
0.1 Introduction

1. Getting Started

  1. SFML and Visual Studio
  2. SFML and Code :: Blocks (MinGW)
  3. SFML and Linux
  4. SFML and Xcode (Mac OS X)
  5. Compiling SFML with CMake

2. System module

  1. Time processing
  2. Потоки
  3. Работа с пользовательскими потоками данных

3. Модуль Window

  1. Открытие и управление окнами
  2. Обработка событий
  3. Работа с клавиатурой, мышью и джойстиками
  4. Использование OpenGL

4. Модуль Graphics

  1. Рисование 2D объектов
  2. Спрайты и текстуры
  3. Текст и шрифты
  4. Формы
  5. Проектирование ваших собственных объектов с помощью массивов вершин
  6. Позиция, вращение, масштаб: преобразование объектов
  7. Добавление специальных эффектов с шейдерами
  8. Контроль 2D камеры и вида

5. Модуль Audio

  1. Проигрывание звуков и музыки
  2. Запись аудио
  3. Пользовательские потоки аудио
  4. Спатиализация: звуки в 3D

6. Модуль Network

  1. Коммуникация с использованием сокетов
  2. Использование и расширение пакетов
  3. Веб-запросы с помощью HTTP
  4. Передача файлов с помощью FTP


SFML time


Unlike many other libraries in which time is represented by uint32 by the number of seconds, or by a fractional number of seconds, SFML does not impose any unit or type for time values. Instead, it leaves this choice to the user, providing the sf :: Time class. All classes and functions that manipulate time values ​​use this class.

sf :: Time represents a period of time (in other words, the time elapsed between two events). This is not a date and time class that represents the current year / month / day / minute / second as a timestamp, it is simply a value indicating the amount of time and providing a way to interpret this value depending on the context of use.

Time conversion


The sf :: Time value can be built from various source units: seconds, milliseconds, and microseconds. There are functions (they are not members of the class) that allow you to convert the value of each of these units to sf :: Time:

sf::Time t1 = sf::microseconds(10000);
sf::Time t2 = sf::milliseconds(10);
sf::Time t3 = sf::seconds(0.01f); 


Note that all three times are equal.

Similarly, sf: Time can be converted back to seconds, milliseconds, and microseconds:

sf::Timetime = ...;
sf::Int64 usec = time.asMicroseconds();
sf::Int32 msec = time.asMilliseconds();
float     sec  = time.asSeconds();


Play with time


sf :: Time is just the amount of time, so this class supports arithmetic operations such as addition, subtraction, multiplication, and so on. Time can also be negative.

sf::Time t1 = ...;
sf::Time t2 = t1 * 2;
sf::Time t3 = t1 + t2;
sf::Time t4 = -t3;
bool b1 = (t1 == t2);
bool b2 = (t3 > t4);


Time measurement


Now that we’ve seen how to manipulate the time value in SFML, let's see how to do what any program needs: measuring past time.

SFML has a very simple class for measuring time: sf :: Clock. There are only two methods in this class: getElapsedTime, designed to get the time since the last restart, and restart, designed to restart the clock.

sf::Clock clock; // часы запускаются
...
sf::Time elapsed1 = clock.getElapsedTime();
std::cout << elapsed1.asSeconds() << std::endl;
clock.restart();
...
sf::Time elapsed2 = clock.getElapsedTime();
std::cout << elapsed2.asSeconds() << std::endl;


Remember that the restart method also returns elapsed time, so you can avoid the slight delay that will be caused if getElapsedTime is called before restart.

The following is an example of using the elapsed time to iterate the game logic update cycle:

sf::Clock clock;
while (window.isOpen())
{
    sf::Time elapsed = clock.restart();
    updateGame(elapsed);
    ...
}


Next article: Streams .

Also popular now: