Add a new variable to a component (Picturebox)

Asked

Viewed 59 times

1

I’m creating a game for a college job, this game consists of several Picturebox, one is the main character who walks, jumps and shoots, the PictureBox of the shooting and the PictureBox of monsters (randomly generated by a Random), currently, when the program detects the collision of the picturebox of the shots with that of the monster, the monster is deleted and the shot also.

What I would like to do is let these monsters having a "life", for example, take 3 shots for the monster to die, but for this I have to create a variable "int life" and correlate it with the PictureBox of the monster that was created and I don’t know how to do it

This is the part of the code where the monsters are created:

Random random = new Random();
int a = random.Next(0, 300);
if (a == 150)
{
  NovoMonstro();
}

This is the Novomonstro Method:

PictureBox monstro = new PictureBox();
Bitmap imagem;
imagem = Properties.Resources.monstro;
monstro.Image = imagem;
monstro.Size = new Size(51, 85);
monstro.SizeMode = PictureBoxSizeMode.StretchImage;
monstro.Tag = "monstros";
monstro.Left = 1024;
monstro.Top = 555;
monstro.BackColor = Color.Transparent;
this.Controls.Add(monstro);
monstro.BringToFront();

This is part of the program of the collision between the shot and the monster:

foreach (Control y in this.Controls)
{
    foreach (Control j in this.Controls)
    {
        if (y is PictureBox && (y.Tag == "bulletD" || y.Tag == "bulletE"))
        {
            if (j is PictureBox && (j.Tag == "monstros" || j.Tag == "monstrosinvertidos"))
            {  
                //detecta se teve colisão entre as picturebox
                if (y.Bounds.IntersectsWith(j.Bounds))
                {
                    this.Controls.Remove(j);
                    this.Controls.Remove(y);
                    contador++;
                }
            }
        }
    }
}

The generation of monsters is inside a Timer and the collision too.

1 answer

1


The solution will be to create a class that extends the type PictureBox and add a property Vida:

using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public class MyPictureBox : PictureBox
    {
        public int Vida { get; set; }
    }
}

Compile the project and use the component MyPictureBox instead of PictureBox native.
From now on you will have the accessible property in the code to be able to manipulate.

  • Yes, I managed to solve the problem yesterday by doing just that, I did not know that it was possible to create a picturebox or any "custom" component and add the type of variable I wish to it, thank you very much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.