use*_*226 4 c++ sdl timedelta sdl-2
我目前用SDL2编程.一切正常,但我的SDL_GetTicks()方法有问题.通常它应该以毫秒为单位返回总应用程序时间,但它总是返回值0的大部分时间,有时返回值1.
我用SDL_INIT_EVERYTHING标志初始化了SDL .
以下代码的问题是循环太快,因此增量时间小于1 ms.有没有一种方法可以达到更高的精度?
#include "Application.hpp"
void Application::Initialize()
{
int sdl_initialize_result = SDL_Init(SDL_INIT_EVERYTHING);
if(sdl_initialize_result < 0)
{
std::cerr << "Failed to initialize SDL !" << std::endl << SDL_GetError() << std::endl;
}
window = SDL_CreateWindow("Project Unknown", 100, 100, 800, 600, SDL_WINDOW_SHOWN);
if(window == nullptr)
{
std::cerr << "Failed to create SDL window !" << std::endl << SDL_GetError() << std::endl;
}
last_update_time = SDL_GetTicks();
}
void Application::Dispose()
{
SDL_DestroyWindow(window);
SDL_Quit();
}
void Application::Render()
{
}
void Application::Update()
{
Uint32 current_time = SDL_GetTicks();
Uint32 delta_time = current_time - last_update_time;
SDL_Event event;
while(SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_QUIT:
{
should_close = true;
}
break;
default:
{
}
break;
}
}
// Update game objects with delta_time
last_update_time = current_time;
}
void Application::Run()
{
Initialize();
should_close = false;
do
{
Render();
Update();
}
while(should_close == false);
Dispose();
}
Run Code Online (Sandbox Code Playgroud)
如果您想要更高的精度,则不能使用SDL_GetTicks(),但还有许多其他选择.如果你想成为独立于平台的你需要小心,但这里有一个可以让你入门的可移植的C++ 11例子:
#include <iostream>
#include <chrono>
typedef std::chrono::high_resolution_clock Clock;
int main()
{
auto t1 = Clock::now();
auto t2 = Clock::now();
std::cout << "Delta t2-t1: "
<< std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count()
<< " nanoseconds" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
在ideone.com上运行这个给了我:
Delta t2-t1: 282 nanoseconds
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7062 次 |
| 最近记录: |