Monday, January 1, 2018

xna - Vector2 to 3D world coordinates


I think I am almost there, but not quite. I am trying to transform a 2D point, (in the following example (100,100)) into 3D world coordinates, in order to draw my 3D Model named TestModel in XNA/Monogame. Here is my attempt:


Matrix[] transforms = new Matrix[TestModel.Bones.Count];
TestModel.CopyAbsoluteBoneTransformsTo(transforms);
ModelMesh mesh = TestModel.Meshes[0];
BasicEffect effect = (BasicEffect)mesh.Effects[0];

float Scale = 1.2f;

effect.View = Matrix.CreateLookAt(new Vector3(0.0f, 0.0f, 6115.0f),
Vector3.Zero, Vector3.Up);
effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f),
aspectRatio, 1.0f, 10000.0f);
effect.EnableDefaultLighting();

//here i am using the function to calculate the world coordinates from (100,100) Point
//it gives me modelPosition = {X:284,0316 Y:384,2054 Z:0,9999364} in this example

Vector3 modelPosition = graphics.GraphicsDevice.Viewport.Project(new Vector3(100, 100, 1),
effect.Projection, effect.View, Matrix.Identity);

effect.World = transforms[mesh.ParentBone.Index] * Matrix.CreateScale(Scale) *
Matrix.CreateTranslation(modelPosition);

//finally i draw the model
mesh.Draw();

I suppose this is the correct function to do it graphics.GraphicsDevice.Viewport.Project, so what exactly am I missing here ? Right now the model is drawn around (393, 444) in the 2D world (instead of (100,100) which is where i am trying to draw it)



Edit: I had wrong numbers before
Edit2: I think the correct function is Unproject, but i still can't get it drawn at (100,100)



Answer



You are right that the correct function is Unproject. Try this:


Vector3 modelPosition = graphics.GraphicsDevice.Viewport.Unproject(
new Vector3(100.0f, 100.0f, 0.01f), // Note the 0.01f!
effect.Projection,
effect.View,
Matrix.Identity);


The 0.01f means you want a point that is 1% of the way between your near and far clip planes (the values you passed into Matrix.CreatePerspectiveFieldOfView). This will work out to 1.0f + 0.01f * (10000.0f - 0.01f) = 100.99f away from the camera position. It should be centered at pixel position (100, 100). Try decreasing the 0.01f value or decreasing your far clip plane distance if the model is too small or not visible.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...