LWJGL 3 get cursor position

How do I get the cursor position? I looked at the GLFW documentation and there is a glfwGetCursorPos(window, &xpos, &ypos) method, but Java has no pointers, so when I tried this method in Java, DoubleBuffers were the arguments. Now when 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 and I can’t understand why (yes, I am setting up a callback in my display class).

+5
source share
1 answer

Java does not support direct pointer support, so LWJGL uses buffers as a workaround. They simply carry a memory address that can be read and written using object methods. This allows you to pass buffers to functions that write values ​​to them, so you can read these values.

The key point here is that you really need to create a buffer in advance to hold the value.

 public static double getCursorPosX(long windowID) { DoubleBuffer posX = BufferUtils.createDoubleBuffer(1); glfwGetCursorPos(windowID, posX, null); return posX.get(0); } 

BufferUtils.createDoubleBuffer(length) is a utility function that creates a buffer. There are different buffers for different primitives, such as int, long, char, float, double, etc. In this case, we need a buffer that can store doublings. The number ( 1 ) that we pass to the method is the number of values ​​that the buffer should store. We can use a buffer with a large size to store several values, as in an array, but here we need only one value.

The get(index) method returns the value at the given index. We just want to read the first value, so we will specify 0. You can also use put(index, value) to store values ​​in the buffer.

Note You might be tempted to do something like the following if you want to get the x and y values:

 DoubleBuffer coords = BufferUtils.createDoubleBuffer(2); glfwGetCursorPos(windowID, coords, coords); double x = coords.get(0); double y = coords.get(1); 

However, this will not work as intended: it will write the y value to index 0 and leave the garbage value (read: random) at index 1. If you want to get both conventions, you need to create a separate buffer for each.

 DoubleBuffer xBuffer = BufferUtils.createDoubleBuffer(1); DoubleBuffer yBuffer = BufferUtils.createDoubleBuffer(1); glfwGetCursorPos(windowID, xBuffer, yBuffer); double x = xBuffer.get(0); double y = yBuffer.get(0); 
+6
source

Source: https://habr.com/ru/post/1235455/


All Articles