Remove items from screen on rectangle click

106 views Asked by At

I've created a rectangle, that has its own class. In the class I have a delegate created, that closes the game.

Creating the delegate:

public event EventHandler ExitRequested = delegate { };

In the update method I tell when to execute it:

if (mouseState.LeftButton == ButtonState.Pressed)
{
    ExitRequested(this, EventArgs.Empty);
}

In my main class I execute the delegate like this (the exitGame is a rectangle):

exitGame.ExitRequested += exitGame_ExitRequested;

What I'm wondering about is there a way how to remove all items from the screen? Lets say it's for a "new game" functionality. I tried to create this functionality the same way I created the exit functionality but I can't figure out how to remove the items...

1

There are 1 answers

0
epicstyle On

As far as I understand, you are trying to remove all game entities / objects in order to start a new game. Usually this is achieved by storing entities in a collection, and then simply removing all collection entries when a 'new game' is needed. As for entities which are not generic, such as the player, usually you just reset every member that needs to be reset; position, points etc.

Say you have a class to hold information about entities, such as enemies:

public class Entity
{
    public Texture2D Sprite;
    public Rectangle Bounds;

    public Entity(Texture2D Sprite, Rectangle Bounds)
    {
        this.Sprite = Sprite;
        this.Bounds = Bounds;
    }    

    public void Update(GameTime gameTime)
    {
        //Movement code here
    }    

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(Sprite,Bounds,Color.White);
    }
}

And you then store all entities in a collection:

public List<Entity> Entities = new List<Entity>();

You update and draw each entity by looping through the collection:

//In main game class
public void Update(GameTime gameTime)
{
    foreach (Entity e in Entities)
        e.Update(gameTime);
}

public override void Draw(GameTime gameTime)
{
    foreach (Entity e in Entities)
        e.Draw(spriteBatch);
}

Then when you want to start a new game, and effectively remove all entities, you can simply remove all entries in the Entities list. (For example using List.Clear(), there are many ways)

Keep in mind this is an example which has not been tested, so to say. This is can be optimized, and is more to give you an idea of why collections are useful for organizing game objects / entities.