0
\$\begingroup\$

I'm making a 2d top down game with lwjgl and am having trouble converting my 2d screen coordinates to 2d world coordinates.

Here's what I have so far

 private Vector2f toWorldCoords(Vector4f eyeCoords) {
    Matrix4f invertedView = Matrix4f.invert(MathUtil.createViewMatrix(camera), null);
    Vector4f rayWorld = Matrix4f.transform(invertedView, eyeCoords, null);
    Vector2f mouseRay = new Vector2f(rayWorld.x, rayWorld.y);
    mouseRay.normalise();
    return mouseRay;
}

public Vector2f screenToWorld(Vector2f mouseCoords) {
    Vector2f normalizedCoords = CursorHandler.getNormalisedDeviceCoordinates();
    Vector4f clipCoords = new Vector4f(normalizedCoords.x, normalizedCoords.y, -1.0f, 1.0f);
    Vector2f worldRay = toWorldCoords(clipCoords);

    return worldRay;
}

I understand it's been asked before, and I've tried following some 3d tutorials that deal with the same topic, but so far I haven't been able to use the code successfully.

Thanks

\$\endgroup\$
0
\$\begingroup\$

It's quite simple really. Your camera must be an orthographic projection so the formula for screen to camera is:

Vector2f cameraPosition = new Vector2f(screenPosition.x - Camera.getWidth() / 2, screenPosition.y - Camera.getHeight() / 2);

Then to world coordinates:

Vector2f worldPosition = cameraPosition.add(Camera.getPosition());

Keep in mind that you'll probably need to invert the camera's position.

Vector2f invertedCameraPosition = camera.getPosition().mul(-1, new Vector2f());
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.