在按键上增加模型的加速度?
Posted
技术标签:
【中文标题】在按键上增加模型的加速度?【英文标题】:Increasing acceleration of model on keypress? 【发布时间】:2018-09-17 13:38:39 【问题描述】:我正在尝试在开放空间中旋转单个立方体。起初,它从静止开始,然后在按键时它应该在特定按键的特定访问中增加旋转速度。
我的初始代码如下所示:
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()
不断增加,当我按住键时它会很快旋转,然后当未按下键时,它会恢复正常旋转速度。
我做错了什么?
【问题讨论】:
【参考方案1】:您可能希望使用 delta-time(自上一帧以来的时间变化)而不是时间。我不确定 GLFW 是否有特定的功能,但你可以这样做:
time = glfwGetTime();
delta = time - lastTime;
// do stuff with delta ...
lastTime = time;
【讨论】:
我曾经也是这么想的。我尝试使用rotationAngle * deltaTime,它确实在按键时旋转,但在未按下时它开始出现故障。 您是否在未按下键时将旋转值重置为 0?【参考方案2】:根据描述,我认为代码是这样的
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,并且每次循环迭代,rotate 函数每次循环旋转一个较大的量。为防止这种情况发生,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 的细节,所以您可能需要更多条件来检查密钥的状态。
【讨论】:
以上是关于在按键上增加模型的加速度?的主要内容,如果未能解决你的问题,请参考以下文章
分享原创开源应用第4期给ili9488,RA8875类显示屏的emWin底层增加DMA加速方案