简体   繁体   中英

Pinning cursor to the middle of the screen?

I'm trying to make a 3D game sort of like minecraft but I don't seem to know how I can make the mouse pin to the center of the screen? I'm using lwjgl to handle mouse inputs. I just want the mouse cursor to stay in the middle of the window that I have created. I saw that there was a Mouse.grab method in the lwjgl mouse class, but when I set it to true, it seems that it doesn't do anything.

First of all, lets look at what Mouse.grab(true) does. There are two distinct operations that this does, all grouped into one call. the first one is to pin the cursor in the centre of the screen, and the second one is to make the cursor invisible. Both of these operations combined will lock the cursor at the centre of the screen. To get input (I assume you are already using this method for camera movement), you will have to use the differential position function of the mouse class, Mouse.getDX() and Mouse.getDY() , which return the change in the cursor position of the cursor(effectively how much the user has moved the mouse) this frame.

Now, In 3D games, you tend to have a crosshair. This is not to be mistaken for the mouse. The crosshair is a UI element draw over the scene (and at the centre of the frame buffer (screen)) that gives the player a point of reference as to where the centre of the screen is, and, in shooter games, where the bullets they shoot will come from, allowing them to aim.

Here, i will provide a short example as to how you can achieve this effect. This code will vary a lot depending on how you are doing graphics, if you are using immediate mode and the fixed pipeline (GL11) or a subsequent version, thus, this will be mostly pseudo code. Feel free to specify which method of rendering you are using and i could give you a more detailed example.

// Your 3D render code here

float aspectRatio = Dislay.getWidth() / (float) Display.getHeight();

// will depend on your rendering implementation
// however the concept stays the same, you switch from a perspective view
// to an orthogonal view
switch_projection_matrix_to_ortho(-1 * aspectRatio, 1 * aspectRatio, -1, 1, -1, 1);

// Apply a crosshair texture
crossahir_texture.bind()
// Draw a quad
quad.draw()

Hope this helped!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM