GLFW中的鼠标滑动事件
以下是glfw3.h
中关于设置鼠标滑动回调函数的方法:
/*! @brief Sets the scroll callback.
*
* This function sets the scroll callback of the specified window, which is
* called when a scrolling device is used, such as a mouse wheel or scrolling
* area of a touchpad.
*
* The scroll callback receives all scrolling input, like that from a mouse
* wheel or a touchpad scrolling area.
*
* @param[in] window The window whose callback to set.
* @param[in] cbfun The new scroll callback, or `NULL` to remove the currently
* set callback.
* @return The previously set callback, or `NULL` if no callback was set or an
* error occurred.
*
* @ingroup input
*/
GLFWAPI GLFWscrollfun glfwSetScrollCallback(GLFWwindow* window, GLFWscrollfun cbfun);
/*! @brief The function signature for scroll callbacks.
*
* This is the function signature for scroll callback functions.
*
* @param[in] window The window that received the event.
* @param[in] xoffset The scroll offset along the x-axis.
* @param[in] yoffset The scroll offset along the y-axis.
*
* @sa glfwSetScrollCallback
*
* @ingroup input
*/
typedef void (* GLFWscrollfun)(GLFWwindow*,double,double);
实际使用中,只要调用这个方法,即可在鼠标或者触摸板产生滑动事件后收到回调事件。
需要注意的是:鼠标只会产生y方向的滑动,xoffset 始终为0。
...
void GLFWBackendInit(int argc, char** argv, bool WithDepth, bool WithStencil)
{
GLFWmonitor* pMonitor = isFullScreen ? glfwGetPrimaryMonitor() : NULL;
s_pWindow = glfwCreateWindow(Width, Height, pTitle, pMonitor, NULL);
if (!s_pWindow) {
OGLDEV_ERROR0("error creating window");
exit(1);
}
glfwMakeContextCurrent(s_pWindow);
if (glfwInit() != 1) {
OGLDEV_ERROR0("Error initializing GLFW");
exit(1);
}
glfwSetScrollCallback(s_pWindow,ScrollCallback);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glFrontFace(GL_CW);
glCullFace(GL_BACK);
glEnable(GL_CULL_FACE);
while (!glfwWindowShouldClose(s_pWindow)) {
s_pCallbacks->RenderSceneCB();
glfwSwapBuffers(s_pWindow);
glfwPollEvents();
}
}
...
static void ScrollCallback(GLFWwindow* window, double xoffset, double yoffset) {
m_pGameCamera->m_pos.z += yoffset;
m_pGameCamera->m_pos.x += xoffset;
cout << "Scroll: (" << xoffset << "," << yoffset << ")" << endl;
}
输出:
实测效果:滚轮每滑动一个单位(鼠标滚轮产生一次机械触感反馈),产生一次 yoffset=1.0的滑动事件。