我一直在研究一个小型3D引擎,试图修理相机并使其不那么生涩。我一直在使用SDL进行输入,虽然它可以正常工作,但如果我按住一个按钮,它会立即移动一次然后暂停,然后开始正常移动,使移动感觉不响应。
我记录了它的GIF,虽然可能有点难以看到发生了什么,但希望它会给出一些想法:
前进然后向右会像:
重要的代码在这里,但如果有必要,请随时提出更多要求:
//Poll events
SDL_Event event;
while (m_EngineState != EngineState::EXIT)
{
m_last = m_current;
m_current = SDL_GetPerformanceCounter();
deltaTime = (double)((m_current - m_last) * 1000 / SDL_GetPerformanceFrequency());
while (SDL_PollEvent(&event))
{
switch (event.type) {
case SDL_QUIT:
m_EngineState = EngineState::EXIT;
break;
case SDL_MOUSEMOTION:
break;
case SDL_KEYDOWN:
m_Keys[event.key.keysym.sym] = true;
break;
case SDL_KEYUP:
m_Keys[event.key.keysym.sym] = false;
break;
}
ProcessEvents();
}
void Engine::ProcessEvents()
{
if (m_Keys[SDLK_w])
{
m_Camera->MoveForward(5.0f*(deltaTime*0.001));
}
if (m_Keys[SDLK_s])
{
m_Camera->MoveForward(-5.0f*(deltaTime*0.001));
}
if (m_Keys[SDLK_d])
{
m_Camera->MoveRight(5.0f*(deltaTime*0.001));
}
if (m_Keys[SDLK_a])
{
m_Camera->MoveRight(-5.0f*(deltaTime*0.001));
}
}
void Camera::MoveForward(float amount)
{
m_pos += m_forward * amount;
}
void Camera::MoveRight(float amount)
{
m_pos += glm::cross(m_forward, m_up) * amount;
}
答案 0 :(得分:3)
不要将SDL_PollEvent
与SDL_KEYDOWN
和SDL_KEYUP
事件一起使用,它受操作系统键盘重复率的影响。这对于打字非常有用,但不适用于相机/播放器控件。请使用SDL_GetKeyboardState(NULL)来查询密钥的当前状态。
例如:
Uint8* keystate = SDL_GetKeyState(NULL);
if(keystate[SDL_SCANCODE_W])
{
m_Camera->MoveForward(5.0f*(deltaTime*0.001));
}
if(keystate[SDL_SCANCODE_S])
{
m_Camera->MoveForward(-5.0f*(deltaTime*0.001));
}
// etc
(编辑答案以考虑评论的更正)