# OpenGL convert mouse position to world coordinates without gluUnproject in Python?

EDIT: I changed the bottom left to -1,-1 and the top right to 1,1, and while I can draw objects within this range, I cannot map the mouse x,y to the world space.

I have been trying to learn OpenGL and my current goal is to move a circle on mouse drag. I have created the circle, but I cannot seem to be able to map my mouse coordinates to the world coordinates using glOrtho. I also set the initial window position to 100, 100, I don't know if that is relevant to the issue though.

For reference this is my init code:

def init():
# select clearing color
glClearColor(0.0, 0.0, 0.0, 0.0)

# initialize viewing values
glMatrixMode(GL_PROJECTION)
glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0)



I know that the glOrtho takes the left, right, bottom, top, near and far values, but when I try to convert to world space coordinates from mouse position(since I only need the x and y so I can calculate distance from the circle's origin) I end up with coordinates in the range 0.0 - 1.25, which makes no sense to me at all, because it should be 0.0 - 1.0.

This is my glutMotionFunc:

def click(x, y):
global current_circle

nx = float(x * SCREEN_SIZE / SCREEN_SIZE)
ny = float(y * SCREEN_SIZE / SCREEN_SIZE)

print("Mouse click", nx, ny)

for circle in circles:
print("Circle center", circle.cx, circle.cy)
if (np.square(nx - circle.cx) + np.square(ny - circle.cy)) <= np.square(circle.r * (SCREEN_SIZE / 10)):
current_circle = circle
current_circle.set_position(nx, ny)

glutPostRedisplay()


Also, why is my window 300x300 when it should be 250x250? I don't set the window size anywhere but the above init function.

• to put screen space coordinates to world space multiply screen space coordinates by inverse view-projection matrix (iirc for perspective projection matrix you would also need to divide result by their w coordinate, not sure for orthogonal projection, probably you don't need to do that). You would also need to make sure your screen space coordinates are normalized to [-1; 1] – Ocelot Oct 7 '20 at 12:21
• Alright, so I managed to get my objects within -1 to 1 and I can't seem to figure out how to convert the mouse coordinates, so I can check if a drawn object is within a certain radius of the mouse for dragging. – Ian Rosenberg Oct 8 '20 at 6:44