C# panel move with collision

前端 未结 2 1335
孤城傲影
孤城傲影 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.

提交回复
热议问题