C# panel move with collision

前端 未结 2 1334
孤城傲影
孤城傲影 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条回答
  • 2021-01-25 15:50

    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.

    0 讨论(0)
  • 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();
    
    0 讨论(0)
提交回复
热议问题