Hack Forums
[C#] Code Snippets for Monogame - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [C#] Code Snippets for Monogame (/showthread.php?tid=5595607)



Code Snippets for Monogame - DatFroschlaich - Apr 8, 2017

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



* - Zilog80 - Apr 9, 2017

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"?


* - DatFroschlaich - Apr 9, 2017

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.


* - gigajew - Apr 14, 2017

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