TIMESTEPS and DELTA TIME

引言

上一节我们整理了应用类和沙盒程序的代码,今天我们继续解决上一节遗留下的问题添加时间步长。

我们想要我们的运动是基于时间的,而不是基于 CPU 的频率。所以我们要做的就是通过时间步长/增量时间(Delta time)实现将现在相机的运动与现实世界的时间联系起来。

时间步

Infinite/ 目录下新建文件夹 Core,创建头文件 Timestep.h

#pragma once

namespace Infinite {

class Timestep
{
public:
Timestep(float time = 0.0f)
:m_Time(time)
{

}

operator float() const { return m_Time; }

float GetSeconds() const { return m_Time; }
float GetMilliseconds() const { return m_Time * 1000.0f; }

private:
float m_Time;
};

}

该头文件非常简单,只内置了一个私有的时间变量和访问器。

接着在 Infinite/Layer.h 中修改 OnUpdate() 方法:

#include "Core.h"
#include "Events/Event.h"
+#include "Core/Timestep.h"

namespace Infinite {

@@ -13,7 +14,7 @@ namespace Infinite {

virtual void OnAttach() {}
virtual void OnDetach() {}
- virtual void OnUpdate() {}
+ virtual void OnUpdate(Timestep ts) {}
virtual void OnEvent(Event& event) {}
virtual void OnImGuiRender() {}

最后在沙盒程序中加入时间步:

@@ -123,22 +123,24 @@ class ExampleLayer : public Infinite::Layer

}

- void OnUpdate() override
+ void OnUpdate(Infinite::Timestep ts) override
{
+ IFN_TRACE("Delta time: {0}s ({1}ms)", ts.GetSeconds(), ts.GetMilliseconds());

if (Infinite::Input::IsKeyPressed(IFN_KEY_LEFT))
- m_CameraPosition.x -= m_CameraMoveSpeed;
+ m_CameraPosition.x -= m_CameraMoveSpeed * ts;
else if (Infinite::Input::IsKeyPressed(IFN_KEY_RIGHT))
- m_CameraPosition.x += m_CameraMoveSpeed;
+ m_CameraPosition.x += m_CameraMoveSpeed * ts;

if (Infinite::Input::IsKeyPressed(IFN_KEY_DOWN))
- m_CameraPosition.y -= m_CameraMoveSpeed;
+ m_CameraPosition.y -= m_CameraMoveSpeed * ts;
else if (Infinite::Input::IsKeyPressed(IFN_KEY_UP))
- m_CameraPosition.y += m_CameraMoveSpeed;
+ m_CameraPosition.y += m_CameraMoveSpeed * ts;

if (Infinite::Input::IsKeyPressed(IFN_KEY_A))
- m_CameraRotation += m_CameraRotationSpeed;
+ m_CameraRotation += m_CameraRotationSpeed * ts;
else if (Infinite::Input::IsKeyPressed(IFN_KEY_D))
- m_CameraRotation -= m_CameraRotationSpeed;
+ m_CameraRotation -= m_CameraRotationSpeed * ts;


Infinite::RenderCommand::SetClearColor({ 0.1f, 0.1f, 0.1f, 1 });
@@ -180,8 +182,8 @@ class ExampleLayer : public Infinite::Layer
Infinite::OrthographicCamera m_Camera;
glm::vec3 m_CameraPosition;
float m_CameraRotation = 0.0f;
- float m_CameraMoveSpeed = 0.1f;
- float m_CameraRotationSpeed = 0.1f;
+ float m_CameraMoveSpeed = 5.0f;
+ float m_CameraRotationSpeed = 180.0f;
};

class Sandbox : public Infinite::Application {

调试