Search code examples
cmacosopenglmacos-carbon

Trying to get a mouse-look camera working in OpenGL on Mac OSX


I've been working on a demo in OpenGL and I've been trying to implement an fps-like mouse-look camera. I've been using Max OSX Leopard, so I've had to use Carbon to get the screen coordinates and return the mouse to the centre of the screen after movement, which works fine most of the time. Below is the related code from my mouse method:

CGPoint pnt;
pnt.x = glutGet(GLUT_WINDOW_WIDTH)/2 + glutGet(GLUT_WINDOW_X);
pnt.y = glutGet(GLUT_WINDOW_HEIGHT)/2 + glutGet(GLUT_WINDOW_Y);

int diffX;
int diffY;
CGGetLastMouseDelta(&diffX, &diffY);

if (diffX == 0 && diffY == 0) return;

if ((diffX) > 0)
    angle += (diffX)/5;
else if ((diffX) < 0)
    angle += (diffX)/5;

if ((diffY) > 0 && pitch < 90)
    pitch += (diffY)/5;
else if ((diffY) < 0 && pitch > -70)
    pitch += (diffY)/5;

CGDisplayMoveCursorToPoint(0, pnt);

The problem is annoyingly simple: The first time CGGetLastMouseDelta is called, it returns the difference between the mouse position before the program started and the centre of the window. This means that when the program begins, the camera is facing the right way as it should be, but as soon as I touch the mouse it jumps to a different position.

I've got another call to centre the cursor inside a function to initialise everything, shown below:

CGPoint pnt;
pnt.x = glutGet(GLUT_WINDOW_WIDTH)/2 + glutGet(GLUT_WINDOW_X);
pnt.y = glutGet(GLUT_WINDOW_HEIGHT)/2 + glutGet(GLUT_WINDOW_Y);
CGDisplayMoveCursorToPoint(0, pnt);

I know very little about Carbon, and have been searching like mad to find an answer, but to no avail. Is there anything else I should be doing to avoid this jumping?


Solution

  • CoreGraphics is not a Carbon API, so there's a good chance you're looking in the wrong place. Try using CGAssociateMouseAndMouseCursorPosition.