Advertisement

Monogame convert pixel coordinate to 3D units

Started by June 19, 2015 02:25 PM
2 comments, last by UgaBugaUgaBuga 9 years, 6 months ago

Does anyone know a precise calculation on converting a pixel to 3D units?

Say for example I have a rectanlge that is 100 position on x and y. How can I compute for the 3D units of those?

This image for example

ask.jpg

You can see that I want to have the red circled thing to be illuminated by the light to have a shadow. But when I tried to convert it to 3D units by dividing the width of the screen to the pixel coordinate its not accurate as you can see the green circled thing has a shadow which should be the red one.

Anyone?

I think what you're looking for is Viewport.Unproject. The method takes a vector and the projection/view/world matrices and returns the unprojected 3D vector.

edit - BTW, your subject says 3D unit to pixel, but your question says pixel to 3D unit...

Advertisement


dividing the width of the screen to the pixel coordinate its not accurate

It appears you're using a perspective projection, so you need to take into consideration how far the object is from the view point. I'm not familiar with Monogame in particular, but it appears Dave Hunt gives part of the solution. Unprojecting will result in a direction vector in 3D. You will need to determine the distance from the source point to the object to fully determine its world position. Think in terms of "picking" - i.e., determining where the unprojected vector intersects the object in world space.

Please don't PM me with questions. Post them in the forums for everyone's benefit, and I can embarrass myself publicly.

You don't forget how to play when you grow old; you grow old when you forget how to play.

Hello. Thanks everyone. Although the unproject method is not that accurate cause I have to add some magic numbers to really position the shadow on the tree.

Edit:

I remove the magic numbers. Turns out I have to calculate the position together with the height and width like this

Vector3 unproj2 = graphics.GraphicsDevice.Viewport.Unproject(new Vector3(rectangle.X + (rectangle.Width / 2), rectangle.Y + (rectangle.Height / 2), 0),
projection, view, world);

This topic is closed to new replies.

Advertisement