Java – lwjgl 3 get cursor position
How do I get the cursor position? I checked the glfw documentation, and there is a method glfwgetcursorpos (window, & XPOS, & YPOS), but Java has no pointer, so when I try this method in Java, I have doublebuffers as a parameter Now I write something like this:
public static double getCursorPosX(long windowID){ DoubleBuffer posX = null; DoubleBuffer posY = null; glfwGetCursorPos(windowID,posX,posY); return posX != null ? posX.get() : 0; }
Posx is null, I can't figure out why (yes, I set a callback in my display class)
Solution
Java does not directly support pointers, so lwjgl uses buffers as a workaround These just wrap a memory address that can be read and written by methods on the object This allows you to pass a buffer to a function that writes values to it so that you can read them
The key point here is that you actually have to create a buffer to store values
public static double getCursorPosX(long windowID) { DoubleBuffer posX = BufferUtils.createDoubleBuffer(1); glfwGetCursorPos(windowID,null); return posX.get(0); }
BufferUtils. Createdoublebuffer (length) is a utility function that creates a buffer Different primitives have different buffers, such as int, long, char, float, double, etc In this case, we need a buffer that can store double precision The number we pass to the method (1) is the number of values that the buffer should be able to store We can use a larger buffer to store multiple values, just like in an array, but here we only need one value
The get (index) method returns the value at the given index We only want to read the first value, so we specify 0 You can also use put (index, value) to store values in a buffer
Note: if you want to get both X and Y values, you might try the following:
DoubleBuffer coords = BufferUtils.createDoubleBuffer(2); glfwGetCursorPos(windowID,coords,coords); double x = coords.get(0); double y = coords.get(1);
However, this does not work as expected: it writes the y value to index 0 and leaves a garbage (read: random) value at index 1 If you want to get two coordinates, you must create a separate buffer for each coordinate
DoubleBuffer xBuffer = BufferUtils.createDoubleBuffer(1); DoubleBuffer yBuffer = BufferUtils.createDoubleBuffer(1); glfwGetCursorPos(windowID,xBuffer,yBuffer); double x = xBuffer.get(0); double y = yBuffer.get(0);