Hi
I'm trying to transform a 3D spacial position to a 2D screen one (I'm looking to align various sprites to 3D objects rendered on the screen).
The following code kind of works although It does not align directly. I'm probably missing something somewhere. Any help/advice appreciated!
Vector3 v = Vector3.Transform(Player.Position, ProjectionMatrix);v = Vector3.Transform(v, ViewMatrix);
Vector2 p = new Vector2(v.X/2, -v.Y/2);
spriteBatch.Draw(Textures["white1x1"], new Rectangle(640+(int)p.X, 360+(int)p.Y, 32, 32), Color.White);
Its the...
Vector2 p = new Vector2(v.X/2, -v.Y/2);
Code line that confuses me. Why I have to halve the X & Y values (including negating Y) to get it close to the 3D object on screen (a Player object).
Any help or advice on accurately working out 3D object screen co-ordinates much appreciated!
BTW... The view an projection matrices are set up as follows...
private void InitializeTransform(){
viewMatrix =
Matrix.CreateLookAt(CameraPosition,
CameraLookAt,
CameraUpVector
);
projectionMatrix =
Matrix.CreatePerspectiveFieldOfView( MathHelper.ToRadians(45),(
float)GraphicsDevice.Viewport.Width / (float)GraphicsDevice.Viewport.Height,1.0f, 10000.0f);
}

Transforming a 3D position to a screen (2D) position
Oguz
You should use Vector4 not Vector3 to calculate transformations. I had written such functions yesterday;
/// <summary>
/// Transforming a 3D position to a 2D position
/// </summary>
/// <param name="vec">3D Position</param>
/// <param name="viewMatrix">View Matrix</param>
/// <param name="projMatrix">Projection Matrix</param>
/// <param name="Width">Screen Width</param>
/// <param name="Height">Screen Height</param>
/// <returns></returns>
static public Point GetProjectPoint(Vector3 vec, Matrix viewMatrix, Matrix projMatrix, int Width, int Height)
{
Matrix mat = Matrix.Identity * viewMatrix * projMatrix;
Vector4 v4 = Vector4.Transform(vec, mat);
return new Point((int)((v4.X / v4.W + 1) * (Width / 2)), (int)((1 - v4.Y / v4.W) * (Height / 2)));
}
If the 3d position may be in outside of the camera's view, you have to add some checking code before return.
Duncan Bayne
Brilliant! Thanks Minahito... That works!
Easy when you know how eh !
Rhubarb