gpt4 book ai didi

C++ DirectX 运动

转载 作者:太空宇宙 更新时间:2023-11-04 13:53:50 26 4
gpt4 key购买 nike

所以我最近一直在研究 DirectX11,但我对它还是很陌生。我现在正在尝试通过翻译来移动一些东西,这就是我所拥有的。我一直在阅读 Frank D Luna 关于 DirectX11 的书,他提供了一个 gameTimer 类,但我真的不确定如何使用增量时间。这是我正在使用的一小段代码。显然这是行不通的,因为每当我不按下键时,时间仍在增加并且是总时间。

// Button down event.
if (GetAsyncKeyState('W') & 0x8000)
{
XMMATRIX carTranslate;
// Every quarter second incremete it
static float t_base = 0.0f;
if( (mTimer.TotalTime() - t_base) >= 0.25f )
t_base += 0.25f;

carPos.x = mTimer.TotalTime();
carPos.y = 1.0f;
carPos.z = 0.0f;
carTranslate = XMMatrixTranslation(carPos.x, carPos.y, carPos.z);

XMStoreFloat4x4(&mCarWorld, XMMatrixMultiply(carScale, carTranslate));
}

最佳答案

通常我们在 while 循环(所谓的“主循环”)中不断渲染帧(重绘屏幕)。要“移动”一个对象,我们只需将它绘制在与前一帧不同的位置。

要一致地移动对象,您需要知道帧之间的时间。我们称之为“增量时间”(dt)。因此,在帧之间,时间增加 dt。给定物体 (v) 的速度(速度),我们可以将位移计算为 dx = dt * v。然后,为了获得当前位置,我们只需将 dx 添加到之前的位置:x += dx

请注意,仅在更新或渲染代码中计算增量不是一个好主意。为了避免分散此功能,我们通常将此计算本地化在计时器/时钟类中。

这是一个简化的例子:

// somewhere in timer class
// `Time` and `Duration` are some time units
class Timer {
Time m_previousTime;
Duration m_delta;
public:
Duration getDelta() const { return m_delta; }

void tick() {
m_delta = currentTime() - m_previousTime; // just subtract
m_previousTime = currentTime; // `current` becomes `previous` for next frame
}
};

// main loop
while(rendering) {
Timer.tick();
Frame(m_Timer.getDelta());
}

void Frame(Duration dt) {
if(keyPressed) {
object.position += dt * object.velocity;
}
}

您现在甚至可以让您的对象随着加速度( throttle 、重力等)移动:

    object.velocity += dt * object.acceleration;
object.position += dt * object.velocity;

希望你明白了!编码愉快!

关于C++ DirectX 运动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22419082/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com