Csharp/C#教程:C#面板随着碰撞而移动分享


C#面板随着碰撞而移动

我是C#和Winforms的新手,并尝试制作一个移动面板。 它应该向右移动直到窗口结束然后向左移动。 它应该从一侧到另一侧反弹。 但经过几个小时的尝试后发生的唯一事情是它向左移动并停止。

使用此表单工具:

Timer = tmrMoveBox (interval: 50) Panel = pnlBox Label = lblXY (for showing the X and Y coordinates in the form) 

这是我的第一个最好的尝试:

 private void tmrMoveBox(object sender, EventArgs e) { if (pnlBox.Location.X <= 316) { for (int i = 0; i = 0) { for (int i = 0; i >= 316; i++) { pnlBox.Location = new Point( pnlBox.Location.X - 2, pnlBox.Location.Y); string BoxLocationToString = pnlBox.Location.ToString(); lblXY.Text = BoxLocationToString; } } } 

第二好的尝试:

 private void tmrMoveBox(object sender, EventArgs e) { int runBox = 1; if(runBox == 1) { while (pnlBox.Location.X  0) { pnlBox.Location = new Point( pnlBox.Location.X - 2, pnlBox.Location.Y); string BoxLocationString = pnlBox.Location.ToString(); lblXY.Text = BoxLocationString; runBox = 1; } } } 

试图使用while循环,但面板刚刚消失。 我不是专家,只是把这个移动面板作为我自己的目标。 希望有人能给我一个提示。

编辑:

Form1.Designer.cs

  this.timer1.Interval = 50; this.timer1.Tick += new System.EventHandler(this.tmrMoveBox); this.timer1.Start(); this.timer1.Step = 2; 

创建一个Timer并订阅Tick事件。 还要创建新的int属性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; } 

并且在ticks事件处理程序中放置你的逻辑,而不是

 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; } 

所以你的盒子每一个计时器滴答一步。

这是我使用的代码:

 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); } 

注意:

要检查碰撞,您应该检查:

你不应该允许面板超越边界甚至一点,所以:

另外最好使用this.ClientRectangle.Width而不是使用硬编码316。

上述就是C#学习教程:C#面板随着碰撞而移动分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注---计算机技术网(www.ctvol.com)

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请点击右边联系管理员删除。

如若转载,请注明出处:https://www.ctvol.com/cdevelopment/1304665.html

(0)
上一篇 2023年2月16日
下一篇 2023年2月16日

精彩推荐