Search code examples
c++openglcameramousemoveglulookat

OpenGL Camera - Move the camera without it snapping back when using SetCursorPos(x,y);?


I have a problem when I try to update my camera.

I want to change the pitch and yaw of the the camera (where its looking) via the mouse But I want the mouse to stay positioned to the center of the window.

//where MouseP.x .y is the mouse position 
//(which is centered to the current window)

//get old position of the mouse
OldP.x = MouseP.x;
OldP.y = MouseP.y;

//work out the distance traveled
Delta.x = MouseP.x - OldP.x;
Delta.y = MouseP.y - OldP.y;

//update the camera(using  distance traveled)
Rot.Yaw -=Delta.x/5;
Rot.Pitch -= Delta.y/5;

//move mouse to the center of the screen
SetCursorPos(CENTER_SCREEN_X,CENTER_SCREEN_Y);

the problem is the camera snaps back to a certain point as the mouse is set to return to the origin.

I want to update the camera by the distance traveled from the origin but not the distance back to the origin.

If I take it out, it works wonderfully but the then mouse can go out of the window.


Solution

  • I believe the issue here is that your block of code probably is inside the catch of a WM_MOUSEMOVE event?

    When you call SetCursorPos, it itself generates another WM_MOUSEMOVE event, so you process this block of code once when you move the mouse, and once again when you call SetCursorPos and it does the opposite of this.

    You probably don't want to put SetCursorPos inside of a WM_MOUSEMOVE event catch, or else you'll generate an endless loop of messages (every SetCursorPos generates another one).

    Perhaps you can move this code outside of the message pump, and just run it once per frame in your update loop: query the current mouse position, make your camera transform, then set the cursor back to the origin.