Search code examples
c#methodologyxna-4.0

XNA C# Code Question


Here is my class I made to draw a HUD:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace Sleyser1
{

public class Hud
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;

    Texture2D tempHUD;
    Rectangle viewportRect;

    SpriteFont HUD;
    Vector2 FontPos;
    Vector2 FontPos2;

    public void Hud()
    {
        HUD = Content.Load<SpriteFont>("HUD");
        FontPos = new Vector2(40, 20);
        FontPos2 = new Vector2(150, 20);

        spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null);

        spriteBatch.Draw(tempHUD, viewportRect, Color.White);

        string output = "Health:";
        string output2 = "Magic:";
        Vector2 FontOrigin = HUD.MeasureString(output) / 2;
        spriteBatch.DrawString(HUD, output, FontPos, Color.Red, 0, FontOrigin, 1.0f, SpriteEffects.None, 0.5f);
        spriteBatch.DrawString(HUD, output2, FontPos2, Color.Blue, 0, FontOrigin, 1.0f, SpriteEffects.None, 0.5f);

        spriteBatch.End();

    }
}
}

So how do I call it from here so that it draws.

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);


        base.Draw(gameTime);
    }

The question I am asking is how do you call a class from a method?


Solution

  • public void Hud()
    

    is actually the constructor of your class, it should not be responsible for drawing (especially since you draw the same class many times and the purpose of the constructor is to ...construct a class)

    So, the first step is to remove this:

    spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null);
    
    spriteBatch.Draw(tempHUD, viewportRect, Color.White);
    
    string output = "Health:";
    string output2 = "Magic:";
    Vector2 FontOrigin = HUD.MeasureString(output) / 2;
    spriteBatch.DrawString(HUD, output, FontPos, Color.Red, 0, FontOrigin, 1.0f, SpriteEffects.None, 0.5f);
    spriteBatch.DrawString(HUD, output2, FontPos2, Color.Blue, 0, FontOrigin, 1.0f, SpriteEffects.None, 0.5f);
    
    spriteBatch.End();
    

    from the constructor and add it to a new class method, such as Draw().

    UPDATE:

    XNA provides a Game class which seems to be the main class of the application. It should contain a reference to an object of your class.

    The spritebatch is also a member of the Game class so it should be passed to the Draw function of your HUD as a parameter. Then all you need to do is call the HUD's Draw method (of a HUD object which is a reachable from the Game object) from the Game's Draw method.