Search code examples
c#picturebox

PictureBox background equal to other PictureBox while moving?


C# Beginner here.

I'm making a 2D Tanks game, and everything's working out nicely so far. Both of my tanks are Picture Boxes, and so is my Missile. The image of the missile and tanks in the PictureBoxes have transparent BackColour properties. The problem is, the background of the missile & tanks are not transparent while on top of the other picturebox (pbBackground). It looks like this.

I'm aware that using different PB's is an inefficient way of going about it, but I've come pretty far and I don't really know any better. Anyways, as you can see, the Missile and Tank PB backgrounds show the form colour. When I downloaded the images, the backgrounds were transparent, I'm sure of it. How do I go about making the background of my PB's truly transparent? (Matching the background of the Overlapped PB?)

I saw this but it doesn't really match my scenario and I don't understand the solution.

UPDATE: Okay, I followed Tommy's advice, is this the right way to go about moving it along pbBackground in a timer constantly changing MissileX and MissileY? Currently this does nothing.

 using (Graphics drawmissile = Graphics.FromImage(pbBackground.Image))
        {
            drawmissile.DrawImage(pbMissile.Image, new Point(MissileX,Convert.ToInt32(MissileY)));
        }

Solution

  • PictureBox is opaque. And PictureBox is not efficient.

    For making games, you should study Paint event which directly draws on your form.

    Bitmap backgroundBitmap = new Bitmap("background");
    Bitmap tankBitmap = new Bitmap("tank");
    
    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.DrawImage(backgroundBitmap, 0, 0);
        e.Graphics.DrawImage(tankBitmap, 30, 30);
    }
    
    private void timer1_Tick(object sender, EventArgs e)
    {
        this.Invalidate(); //trigger Form1_Paint to draw next frame
    }