用计时器移动对象

时间:2017-03-15 08:12:07

标签: c# winforms timer

我有一个物体在一个形状中有一个对角线的运动,初始位置是中心,我想在物体的角落处停止运动时将运动返回到初始位置,谢谢帮助,我有第一个动作,但我现在不知道如何返回。

public void functionThread()
{
   var timer2 = new Timer();
   timer2.Interval = 50;
   timer2.Enabled = true;

   timer2.Tick += (s, e) => panel1.Location = new Point(panel1.Location.X - 5, panel1.Location.Y - 5);
}

2 个答案:

答案 0 :(得分:2)

timer2声明移出您的函数并进入表单,如下所示:

public partial class Form1 : Form
{
    System.Windows.Forms.Timer timer2 = new System.Windows.Forms.Timer();

    public Form1()
    {
    }

functionThread制作Tick事件的方法中,使代码更易于阅读和维护

timer2.Tick += Timer2_Tick; 

Timer2_Tick方法中检查面板的位置并在必要时停止计时器

private void Timer2_Tick(object sender, EventArgs e)
{
    if (panel1.Left == 0 || panel1.Top == 0)
    {
        timer2.Stop();
    }
    else
        panel1.Location = new Point(panel1.Location.X - 5, panel1.Location.Y - 5);
}

答案 1 :(得分:0)

此代码使面板从左向右移动,其起始位置为10,10(BasePoint),一旦面板撞到边缘,它将重新设置面板,以便它可以再次移动。一旦你点击这个bool,你也可以停止计时器,只有改变才能全局声明计时器,这个答案由:Nino提供

bool HitEdge = false;
Point BasePoint = new Point(10,10);
Timer timer2 = new Timer();

public void functionThread()
{ 
    timer2.Interval = 50;
    timer2.Enabled = true;
    timer2.Tick += timer2_Tick;
}

private void timer2_Tick(object sender, EventArgs e)
{
    if((panel1.Left + panel1.Width) >= this.Width)
    {
        HitEdge = true;
    }
    if (!HitEdge )
    {
        panel1.Left += 15;
    }
    else
    {
        panel1.Location = BasePoint;
        HitEdge = false;
    }
}