Search code examples
c#xnamonogame

Monogame - Reload a sprite again


I'm making a 2D game using Monogame. My character loads to the game fine, however when a user presses the T key, I want my character to reload again (As if the character has teleported.)

I have loaded the player content in the LoadContent() function like so:

player.Load(Content);

And in the Draw() function, I have tried to reload the character again when 'T' is pressed by doing:

if (Keyboard.GetState().IsKeyDown(Keys.T))
{
    player.Draw(spriteBatch);
}

and/or,

if (Keyboard.GetState().IsKeyDown(Keys.T))
{
    player.Load(Content);
}

but neither of these seem to work.

My question is, what is the correct way to successfully load the character again and where do I place this if statement?

UPDATE:

Here's my player.Load() method used in the player class:

public void Load (ContentManager Content)
{
    texture = Content.Load<Texture2D>("danPlayer");    
}

Solution

  • You already have a function for loading the character, which is good. Now:
    1) The Draw function is meant for drawing. It's running (kind of) async from the game. All your game logic should be in the Update function.
    2) You have to know how to check if a keyboard button is clicked, not if it is being held down, because this way, the character will Load as long as you are holding the 'T' key. No matter how fast you click 'T' key, the way you are doing it, you'll fire the Load function at least 2-3 times.
    3) To check this, you'll need 2 variables holding the current and the last state of keyboard, and all your game logic should be in between the updates for new and old keyboard state. You could also create a simple function to check for Click(Keys key) and Hold(Keys key)

    KeyboardSate ksNew, ksOld;
    protected override void Update (GameTime gameTime)
    {
        ksNew = KeyboardSate.GetState();
    
        *your logic here*
    
        if (Click(Keys.T))
            player.Load(Content);
    
        ksOld = ksNew;
    }
    
    private bool Click(Keys key)
    {
        return ksNew.IsKeyDown(key) && ksOld.IsKeyUp(key);
    }
    
    private bool Hold(Keys key)
    {
        return ksNew.IsKeyDown(key);
    }