在按键上增加模型的加速度?

问题描述 投票:0回答:2

我正试图在开放空间中旋转一个立方体。首先,它开始静止,然后在按键时它应该在特定按键上的特定访问中增加旋转速度。

我的初始代码如下所示:

model = glm::rotate(model, glm::radians(rotationAngle.x * glfwGetTime()), glm::vec3(1.0f, 0.0f, 0.0f));
model = glm::rotate(model, glm::radians(rotationAngle.y * glfwGetTime())), glm::vec3(0.0f, 1.0f, 0.0f));
model = glm::rotate(model, glm::radians(rotationAngle.z * glfwGetTime())), glm::vec3(0.0f, 0.0f, 1.0f)

在一般的按键,比如A,代码看起来像这样:

if(glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS){
    rotationAngle.x += 0.01;
}

这会增加旋转速度,但由于glfwGetTime()不断增加,当我按住键时它会非常快地旋转,然后当按键未按下时,它会返回到正常旋转速度。

我能做错什么?

c++ opengl glfw glm-math
2个回答
3
投票

您可能希望使用delta-time(自上一帧以来的时间变化)而不是时间。我不确定GLFW是否具有特定功能,但您可以这样做:

time = glfwGetTime();
delta = time - lastTime;

// do stuff with delta ...

lastTime = time;

0
投票

从描述中,我想到代码是这样的

while(condition)
{
    model = glm::rotate(model, glm::radians(rotationAngle.x * glfwGetTime()), glm::vec3(1.0f, 0.0f, 0.0f));
    model = glm::rotate(model, glm::radians(rotationAngle.y * glfwGetTime())), glm::vec3(0.0f, 1.0f, 0.0f));
    model = glm::rotate(model, glm::radians(rotationAngle.z * glfwGetTime())), glm::vec3(0.0f, 0.0f, 1.0f));

    if(glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
    {
        rotationAngle.x += 0.01;
    }
}

按住键时,rotationAngle每次增加0.01,每次循环迭代时,旋转功能每个循环旋转一个更大的量。为了防止这种情况发生,if语句只应在从“未压缩”变为“按下”时激活。我们可以用旗帜做到这一点。

while(condition)
{
    static bool keyDown = false;

    model = glm::rotate(model, glm::radians(rotationAngle.x * glfwGetTime()), glm::vec3(1.0f, 0.0f, 0.0f));
    model = glm::rotate(model, glm::radians(rotationAngle.y * glfwGetTime())), glm::vec3(0.0f, 1.0f, 0.0f));
    model = glm::rotate(model, glm::radians(rotationAngle.z * glfwGetTime())), glm::vec3(0.0f, 0.0f, 1.0f));

    if(glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
    {
        // We don't combine !keyDown in the outer if statement because
        // we don't want the else statement to be activated whenever either 
        // statement is false.

        // If key was not previously pressed, then activate. Otherwise, 
        // key is already down and we ignore this.
        if(!keyDown)
        {
            rotationAngle.x += 0.01;
            keyDown = true;
        }
    }
    // Once you let go of the key, this part activates and resets the flag 
    // as well as the rotation angle.
    else
    {
        rotationAngle.x = 0.0;
        keydown = false;
    }
}

它应该或多或少看起来像这样。我不知道glfwGetKey的具体细节,因此您可能需要更多条件来检查密钥的状态。

© www.soinside.com 2019 - 2024. All rights reserved.