Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

C# 

Code Snippets for Monogame

I will post some interesting code snippets here from time to time which you can use in your Monogame or XNA game projects. These pieces of code helped myself a lot in the past.
Eventually I will start making a tutorial here about coding a game with C# and XNA.


Let's start with centering text:
Code
//At first you have to load a sprite font, in my project it's called "Font"
SpriteFont SF = Content.Load<SpriteFont>("Font");
//you can create fonts via the MG Pipeline

//The string that will be drawn
string Text = "some nice text";

//The position of the drawn string
//This will be centered exactly at the middle of the game window

float x = GraphicsDevice.Viewport.Width / 2 - SF.MeasureString(Text).X / 2;
float y = GraphicsDevice.Viewport.Height / 2 - SF.MeasureString(Text).Y / 2;

Vector2 Position = new Vector2(x, y);

//put the whole code above in the LoadContent method or, if you have one in your class, the constructor.

//Then we can finally draw our string
//I will use the standard SpriteBatch parameter of the Draw method

spriteBatch.Draw(SF, Position, Text, Color.White);
//this code has to be put into the Draw method
What's that code supposed to do?

If some copy this 'snippet' simply will get a big fail.

Where is spritebatch begin/end?
Where is Draw/Update/Loadcontent... methods?
Where do yo put this snippet, on Draw or on Update?
How you Load a "font"?
It's a SNIPPET. It's not meant for someone who doesn't know how to use Monogame.
When I would explain every little thing, then it would be a tutorial, but this isn't one.

Anyway, I edited the post and added some information, that even those with little experience should be able to understand it.

I will write a tutorial how to do all things that are needed soon.

By the way, it stands there what this code is supposed to do, and how to load a font.
If this is a snippet to draw in the center of a surface then you could have just said pos x=width /2 - object.width/2 and pos y = height /2 - object.height /2
[Image: Syr3DlV.png]


Possibly Related Threads...
Thread / Author Replies Views Last Post
[Python] by SIM-5432905Nov 16, 2023 04:06 PM 8 281 Nov 16, 2023 04:06 PM
Last Post: Hackers
[C#] by fungooseSep 2, 2018 02:08 PM 0 239 Sep 2, 2018 02:08 PM
Last Post: fungoose
[.NET] by XoggOct 4, 2017 10:05 PM 31 2,058 Oct 4, 2017 10:05 PM
Last Post: Xogg