n00bster
n00bster

Reputation: 2595

LWJGL cursor trouble when resizing

I have probably a simple math problem that I'm having surprisingly hard time figuring out. I have a resizable LWJGL (OpenGL) window. The game I'm making is in 2D, but I use glFrustum() to get depth for my sprites. Here's a (little bit simplified) snippet from my projection code:

double divider = 64.0;
double left = -vw / divider;
double right = vw / divider;
double bottom = vh / divider;
double top = -vh / divider;

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(left * aspect, right * aspect, bottom, top, 8, 65536);

float zModifier = -256;
float vRatio = Game.HEIGHT / Display.getHeight();

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(-vw / 2.0f, -vh / 2.0f, zModifier * vRatio);

(I must admit that I don't understand the frustum bit very well, I found this piece of code somewhere in the Internet and it has served me well...)

However, I am rendering my own cursor with a sprite, and switch to native cursor when the cursor comes in contact with the window border. This worked all well until I made the window resizable.

Now my problem is, when I resize the window, the native cursor is "out of sync" with the sprite cursor relative to the vRatio. It "jumps" a bit, or a bit more, depending of the resized window size.

When the sprite cursor comes in contact with border, I do the following:

  1. Hide the sprite cursor
  2. Show the native cursor
  3. Set the native cursor's location to sprite cursor's location (this does not work correctly anymore)

I feel like there's a simple math solution to this but I cannot figure it out (I've tried things... but..).

I hope my question isn't too vague, and that I provided enough information!

Upvotes: 1

Views: 475

Answers (1)

Robert Kühne
Robert Kühne

Reputation: 908

At first your window size matches that of OpenGLs. But when you resize the window, the projection must change. So at least a scaling factor is added. This explains why the cursors are not in sync.

If you want to get them in sync all the time, you have to map window coordinates into world coordinates. This can be accomplished with gluUnProject OpenGL: gluUnProject. You are already doing that by hand but without considering the changes in resolution which leads to your problem.

For completeness, the reverse, going from world coordinates to window coordinates, is also possible OpenGL: gluProject

When using these functions, you have to get your hands on model matrix, projection matrix and the viewport. Use the functions of the glGet* family for that purpose. Be sure to load these matrices at a point where they are set correctly!

Upvotes: 1

Related Questions