C# panel move with collision

…衆ロ難τιáo~ 提交于 2019-12-02 07:20:25

Create a Timer and subscribe to Tick event. Also create new int property Step.

System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
int Step;

Form1 () 
{
     InitializeComponent()
    ....
     t.Interval = 15000; // specify interval time as you want
     t.Tick += new EventHandler(timer_Tick); 
     t.Start();

     this.Step = 2; 
}

And in ticks event handler put your logic, without while

void timer_Tick(object sender, EventArgs e)
{
        if (pnlBox.Location.X >= 316)
        {
            Step = -2;
        }
        if (pnlBox.Location.X <= 0) 
        {
            Step = 2;
        }

        pnlBox.Location = new Point(
        pnlBox.Location.X + Step , pnlBox.Location.Y);
        string BoxLocationString = pnlBox.Location.ToString();
        lblXY.Text = BoxLocationString;
}

So your box will move on one step per one timer tick.

Here is the code I used:

int d= 10;
private void timer1_Tick(object sender, EventArgs e)
{
    //Reverse the direction of move after a collision
    if(panel1.Left==0 || panel1.Right==this.ClientRectangle.Width)
        d = -d;

    //Move panel, also prevent it from going beyond the borders event a point.
    if(d>0)
        panel1.Left = Math.Min(panel1.Left + d, this.ClientRectangle.Width - panel1.Width);
    else
        panel1.Left = Math.Max(panel1.Left + d, 0);
}

Note:

To check the collision you should check:

  • Collision with left: panel1.Left==0
  • Collision with right: panel1.Right==this.ClientRectangle.Width

You should not allow the panel goes beyond the borders even a point, so:

  • The maximum allowed value for your panel left is this.ClientRectangle.Width - panel1.Width

  • The minimum allowed value for your panel left is 0

Also It's better to use this.ClientRectangle.Width instead of using hard coded 316.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!