简体   繁体   中英

Moving Pictureboxes from left to right

I have 4 pictureBoxes. I need they move until hit right side and then move to left side and again. But after 1st picturebox hit left side other move closer to him. How fix it??

    int changePositionX;
    bool change = true;

    private void timer1_Tick(object sender, EventArgs e)
    {
        foreach (Control x in this.Controls)
        {
            if (x is PictureBox && x.Tag != null && x.Tag.ToString() == "enemy")
            {


                if (x.Location.X < 750 && change == true)
                {
                    changePositionX = x.Location.X + 50;
                    x.Location = new Point(changePositionX, x.Location.Y);                       
                }
                else
                {
                    change = false;
                }
                if(x.Location.X >= 100 && change == false)
                {
                    changePositionX = x.Location.X - 50;
                    x.Location = new Point(changePositionX, x.Location.Y);                                             
                }
                else
                {
                    change = true;
                }                    
            }
        }
    }

Try it like this instead:

bool goingRight = true;

private void timer1_Tick(object sender, EventArgs e)
{
    foreach (PictureBox pb in this.Controls.OfType<PictureBox>())
    {
        if (pb.Tag != null && pb.Tag.ToString() == "enemy")
        {
            if (goingRight)
            {
                if (pb.Location.X < 750)
                {
                    pb.Location = new Point(pb.Location.X + 50, pb.Location.Y);                           
                }
                else
                {
                    goingRight = !goingRight; // switch directions
                }
            }
            else // going left
            {
                if (pb.Location.X >= 100)
                {
                    pb.Location = new Point(pb.Location.X - 50, pb.Location.Y);
                }
                else
                {
                    goingRight = !goingRight; // switch directions
                }
            }
        }                               
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM