yeahBlitz
yeahBlitz

Reputation: 41

adding a 2D Sprite with a mouse click

i'm just beginning to code in C# / XNA I've made a very simple little program in XNA, its a drawn rectangle, with 3 randomly generated balls inside, the balls are defined in their own class and I've been following this tutorial http://www.bluerosegames.com/brg/xna101.aspx

the balls are generated using

int ballCount = 3;

and what i wanted to do is make it so a mouse click would increase the int by 1, adding another ball to the screen

my code looks like this, but I'm not sure if it's right / possible

         mouseStateCurrent = Mouse.GetState();

        if (mouseStateCurrent.LeftButton == ButtonState.Pressed &&
            mouseStatePrevious.LeftButton == ButtonState.Released)
        {

            ballCount = ballCount+1;

        }

        mouseStatePrevious = mouseStateCurrent;

any help advice would be helpful :)

i am using a code to draw the balls already that looks like this

        spriteBatch.Begin();
        spriteBatch.Draw(debugColor, TextBox, Color.White);
        spriteBatch.Draw(background, backgroundRectangle, Color.White);
        foreach (BouncingBall ball in balls)
        {
            ball.Draw(spriteBatch);
        }
        spriteBatch.End();
        base.Draw(gameTime);

is it possible to edit this to get the "click to add balls" effect?

Upvotes: 0

Views: 1071

Answers (2)

Neil Knight
Neil Knight

Reputation: 48537

If balls is defined as a List<BouncingBall> that is accessible to the Game class, in your MouseClick event you can use balls.Add(new BouncingBall());. Because you are using a foreach loop, it will increment the number of balls each loop and your Draw code will already cater for any new balls added.

Upvotes: 3

Mike Diaz
Mike Diaz

Reputation: 2065

In your draw method you can do something like

 protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
        spriteBatch.Begin();
      for(var i=0;i<ballcount;i++)
      {
          spriteBatch.Draw()
      }
        spriteBatch.End();
        base.Draw(gameTime);
    }

Upvotes: 1

Related Questions