C# panel move with collision

前端 未结 2 1438
孤城傲影
孤城傲影 2021-01-25 14:57

I am new to C# and Winforms and try to make a moving panel. It should move right until the end of my window and then back left. It should bounce from side to side. But the only

2条回答
  •  Happy的楠姐
    2021-01-25 15:53

    Depending on what you're using:

    1. Windows Forms
    2. WPF

    Create a Timer and subscribe to the Tick event. Also, you should create new int property Step.

    1. Windows Forms:

    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.

    1. WPF:

    As System.Windows.Forms.Timer is not available, you may use System.Windows.Threading.DispatcherTimer:

    using System.Windows.Threading;
    
    DispatcherTimer t = new DispatcherTimer();
    t.Interval = new TimeSpan(0, 0, 15); // hours, minutes, seconds (there are more constructors)
    t.Tick += Timer_Tick;
    t.Start();
    

提交回复
热议问题