GLFW: input & timeGLFW 3.0

glfwSetCursorPosCallback

Registers a function called every time the mouse moves, with the new cursor position.

Signature

GLFWcursorposfun glfwSetCursorPosCallback(GLFWwindow* window, GLFWcursorposfun callback);

How it works

The callback receives the NEW position, not how far the mouse moved. To turn a camera you need the movement (the offset), so keep the previous position and subtract: dx = x - lastX, dy = lastY - y (reversed, because screen y grows downwards while "looking up" is positive pitch).

On the very first call there is no previous position yet. Store it and skip the movement, or the camera jumps the first time the mouse enters the window.

Parameters

windowGLFWwindow*

The window to listen to.

callbackGLFWcursorposfun

Your function, void f(GLFWwindow* window, double xpos, double ypos), or NULL.

Return value

The callback that was set before, or NULL.

Errors

When the call is invalid it does nothing and sets an error, which glGetError returns:

GLFW_NOT_INITIALIZED
Called before glfwInit or after glfwTerminate.

Example

example.cpp
1bool firstMouse = true;
2double lastX, lastY;
3
4void onCursor(GLFWwindow*, double x, double y) {
5    if (firstMouse) { lastX = x; lastY = y; firstMouse = false; }
6    float dx = float(x - lastX), dy = float(lastY - y);   // y reversed
7    lastX = x; lastY = y;
8    yaw   += dx * 0.1f;
9    pitch += dy * 0.1f;
10    pitch = std::clamp(pitch, -89.0f, 89.0f);
11}
12
13glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
14glfwSetCursorPosCallback(window, onCursor);
Official GLFW documentation