简体   繁体   中英

problems with getting the mouse coordinates from GLFW in Java (potentially a bytebuffer issue)

I recently made the switch from LWJGL 2 to LWJGL 3, and after a few hours of gaping at the documentation and assembling a program to use it, I had this code. note that the code in the methods are all static, and Eclipse is giving me no issues with the code related to this. Also, note that changing it from allocateDirect to allocate had no effect.

  //At the beginning of the class declaration: public static ByteBuffer mouseXb=ByteBuffer.allocateDirect(8), mouseYb=ByteBuffer.allocateDirect(8); public static double mouseX=0,mouseY=0; //Then later, in another method in the same class glfwPollEvents(); glfwGetCursorPos(window, mouseXb, mouseYb); mouseX=mouseXb.getDouble(); mouseY=mouseYb.getDouble(); System.out.println(mouseX+", "+mouseY); mouseXb.flip(); mouseYb.flip(); 

Oddly, though, I get values like: (Also note that they only changed when the mouse moved around in the window, and never when outside of it, nor when the mouse was not moving)

 2.0857E-317, 2.604651E-317 3.121831E-317, 2.604651E-317 5.1940924E-317, 2.604651E-317 7.2664804E-317, 2.604651E-317 6.7490474E-317, 2.0865855E-317 4.6771653E-317, 7.785178E-317 5.19561E-317, 5.7129166E-317 

Okay, I fixed the issue, but I'll leave this post here in case anyone else has the same problem. It turns out GLFW uses little endian and Bytebuffers are big endian by default.

You can solve the issue by adding this (if you were using my code): mouseYb.order(ByteOrder.LITTLE_ENDIAN); mouseXb.order(ByteOrder.LITTLE_ENDIAN); mouseYb.order(ByteOrder.LITTLE_ENDIAN); mouseXb.order(ByteOrder.LITTLE_ENDIAN);

I'm still quite new to LWJGL 3 myself, and had some trouble with the ByteBuffers. After a bit of looking around I found this page: LWJGL - Bindings FAQ .

In the org.lwjgl package there's a class called BufferUtils, which has a static function to generate a ByteBuffer. From the source code I noticed they called the order method too, just like with your fix, albeit with a different parameter:

public static ByteBuffer createByteBuffer(int capacity)
{
    return BUFFER_ALLOCATOR.malloc(capacity).order(ByteOrder.nativeOrder());
}

The FAQ recommends using this option. Apparently your code's working fine now, but I just thought you should know in case you run into any problems in the future.

Also, thanks for your code snippet, I didn't know how to work the ByteBuffers, and now I do!

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