Advertisement Jump to content
Sign in to follow this  

OpenGL Screen Coords to World Coords

This topic is 969 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am trying to convert screen coords to world cords so that I can move an object with the mouse cursor in C++ using glew and glfw. I've been following an article on raycasting, which gets me part of the way.


In my program, I am able to move the object but it either moves too far or too little.



The code I have right now is:


Projection/View Declaration

	GlobalProjection = glm::perspective(1.0f, 4.0f / 3.0f, 1.0f, 1024.1f);

	GlobalView = glm::lookAt(
		glm::vec3(0, 0, 1024.0f), // Camera location
		glm::vec3(0, 0, 0), // Where camera is looking
		glm::vec3(0, 1, 0) // Camera head is facing up

Transform Function

glm::vec3 Application::viewToWorldCoordTransform(int mouse_x, int mouse_y) {
	double x = 2.0 * mouse_x / 1024 - 1;
	double y = 2.0 * mouse_y / 768 - 1;

	glm::mat4 ProjectView = GlobalProjection * GlobalView;
	glm::mat4 viewProjectionInverse = inverse(ProjectView);

	glm::vec4 screenPos = glm::vec4(x, -y, -1.0f, -1.0f);
	glm::vec4 worldPos = viewProjectionInverse * screenPos;
	return glm::normalize(glm::vec3(worldPos));

I have a loose understanding of how this all works, and I get lost when inverse is used.


If there's any existing code out there that I can get referred to or if someone can point out where I'm going awry I would appreciate it.

Share this post

Link to post
Share on other sites

The inverse is used to convert from clip space to world space. 

I think the normalization of the world pos in the end could be the problem. Because you are calculating the world pos this is not correct. Normalization is only defined for vectors and not for points.

Another thing I noticed is your screenPos normally the last component should be 1.0f and not -1.0f for a point. If this would be a vector it would be 0.0f.

Share this post

Link to post
Share on other sites

It looks like normalization was part of the problem, and the adjustment to the 4th component of the screenPos helped save me some time from troubleshooting more.


Thank you! =)

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using, you agree to our community Guidelines, Terms of Use, and Privacy Policy. is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!