Selaa lähdekoodia

Get initial mouse pos on init, pass it to the InputManager

Toni Helenius 7 vuotta sitten
vanhempi
commit
ca81975988

+ 34 - 0
jme3-lwjgl3/src/main/java/com/jme3/input/lwjgl/GlfwMouseInput.java

@@ -39,6 +39,7 @@ import com.jme3.input.event.MouseMotionEvent;
 import com.jme3.system.lwjgl.LwjglWindow;
 import com.jme3.util.BufferUtils;
 import java.nio.ByteBuffer;
+import java.nio.DoubleBuffer;
 import java.nio.IntBuffer;
 import java.util.ArrayDeque;
 import java.util.HashMap;
@@ -197,6 +198,7 @@ public class GlfwMouseInput implements MouseInput {
             currentHeight = height.get();
         }
 
+        initCurrentMousePosition(window);
         glfwSetCursorPosCallback(window, cursorPosCallback = new GLFWCursorPosCallback() {
             @Override
             public void invoke(final long window, final double xpos, final double ypos) {
@@ -226,11 +228,40 @@ public class GlfwMouseInput implements MouseInput {
             }
         });
 
+        if(listener != null) {
+            sendFirstMouseEvent();
+        }
+
         setCursorVisible(cursorVisible);
         logger.fine("Mouse created.");
         initialized = true;
     }
 
+    private void initCurrentMousePosition(long window) {
+        DoubleBuffer x = BufferUtils.createDoubleBuffer(1);
+        DoubleBuffer y = BufferUtils.createDoubleBuffer(1);
+        glfwGetCursorPos(window, x, y);
+        mouseX = (int) Math.round(x.get());
+        mouseY = (int) currentHeight - (int) Math.round(y.get());
+    }
+
+    /**
+     * Send the input listener a special mouse-motion event with zero deltas in
+     * order to initialize the listener's cursor position.
+     */
+    private void sendFirstMouseEvent() {
+        assert listener != null;
+
+        int xDelta = 0;
+        int yDelta = 0;
+        int wheelDelta = 0;
+        MouseMotionEvent evt = new MouseMotionEvent(mouseX, mouseY, xDelta, yDelta,
+                mouseWheel, wheelDelta);
+        evt.setTime(getInputTimeNanos());
+
+        listener.onMouseMotionEvent(evt);
+     }
+
     @Override
     public boolean isInitialized() {
         return initialized;
@@ -308,6 +339,9 @@ public class GlfwMouseInput implements MouseInput {
     @Override
     public void setInputListener(RawInputListener listener) {
         this.listener = listener;
+        if (listener != null && initialized) {
+            sendFirstMouseEvent();
+        }
     }
 
     @Override