0

I want to draw text and an image on a specific position in 3D Space. The scene is rendered in 3D and I want to display a rendered 2D Text and an image on a XYZ-Coordinate.

I have the World, View, Projection Matrices from the scene and the ViewPort. I don't want to render a real 3D-Font and I also don't want to display the image with texture vertices.

I've tried some matrix multiplications with the transformation matrix and I also tried to use the basic effect as parameter for the begin-method. But non of them worked for me.

        eff.World = Graph3DGame.Current.currentWorld;
        eff.View = Graph3DGame.Current.currentView;
        eff.Projection = Graph3DGame.Current.currentPerspective;

        spriteBatch.Begin(0, null, null, null, null, eff);
        spriteBatch.DrawString(Fonts.Math, "hello, world!", new Vector2(100,100), Color.Blue);
        spriteBatch.End();

Hope anyone could help.

1 Answers1

2

If you have the x,y,z coordinate, you can find the actual corresponding 2d coordinate on screen by projecting the 3d coordinates using the viewport. Basically this should work:

var position3d = new Vector3(1,1,1);

var viewport = GraphicsDevice.Viewport;
var position2d = viewport.Project(position3d, projectionMatrix, viewMatrix, worldMatrix);

The position2d value will have a z value, which you can ignore if you want.

You can then draw you text by using this (if you want i centered):

var text = "Hello, world!";
var measure = myFont.Measure("Hello, world!");

var centeredPosition = new Vector2(position2d.X - measure.X / 2, position2d.Y - measure.Y / 2);

spriteBatch.Begin();
spriteBatch.DrawString(myFont, text, centeredPosition, Color.Blue);

Hope that helps.

abousquet
  • 576
  • 3
  • 13