Rendering Text via SpriteBatch


#1

Hello,

I am trying to figure things out with Xenko, an my current goal would be to get a certain text appear on screen.

I am using BasicCameraController sync script from one of the example projects (1.9 engine version, of course), and adding some code I figured out from engine sources and documentation:

 public override void Update () {
        if (DefaultSpriteBatch == null)
            DefaultSpriteBatch = new SpriteBatch(Game.GraphicsDevice);
        if (DefaultFont == null)
            DefaultFont = Content.Load<SpriteFont>("XenkoDefaultFont");


        PrintString();
        ProcessInput();
        UpdateTransform();
    }

private void PrintString () {
            DefaultSpriteBatch.Begin(Game.GraphicsContext);
            DefaultSpriteBatch.DrawString(DefaultFont, "Whatever", new Vector2(0.5f, 0.5f), Color.Red);
            DefaultSpriteBatch.End();

        }

No text shows up on the screen. What am I doing wrong?


#2

Hi @Petr_Dyachikhin

Welcome to the community.

You have to add a renderer to the Composition. This is covered in the Simple Sprite example in BallScript.cs.

Documentation doesn’t really explain this well. :disappointed: But they are working on it…

cheers,
dfkeenan


#3

Hi,

Thanks, it actually works :slight_smile:

Now, how do I make sure the text renders in foreground instead of behind all meshes?


#4

Wow, your models must be really close to the camera :smile:

There are a bunch of options. Starting from the more complex option of setting up a multi-layer render composition. The simplest but possibly not the best option would be to call Begin with a depth stencil state, like

spriteBatch.Begin(context.GraphicsContext,depthStencilState:DepthStencilStates.None);

#5

Nice, it works with depth stencil just fine, thank you.
I saw this stencil code in the engine sources, but did not know what it does. Now I know :slight_smile:


#6

Hello, I’m trying to do this as well, but the BallScript demo is gone (guessing it’s obsolete so even if I found it, it wouldn’t be helpful?)

I’m trying to render text on a SpriteBatch into a UI element (is this the correct way to do it? I already know how to do it with the TextBlock element, but I want to add colored text, so I’m assuming I need a SpriteBatch, just to avoid the XY problem). I’m already calling the SpriteBatch Begin, DrawString and End methods, but I can’t figure out how to put said SpriteBatch into the world, I don’t know which type of UI Element I need or what methods I should call on them. I’ve looked at some of the source code of the demos but I don’t quite see how I’m supposed to do it.


#7

Hello.

Sorry I won’t be able to help you with this one, I’ve switched to another engine quite some time ago :frowning: