C#面板随着碰撞移动它应该向右移动直到窗口结束,然后向左移动。它应该从一侧弹到另一侧。但经过几个小时的尝试,唯一发生的事情是它向左移动并停了下来。使用此表单工具:Timer=tmrMoveBox(interval:50)Panel=pnlBoxLabel=lblXY(用于在表单中显示X和Y坐标)这是我的第一个最佳尝试:privatevoidtmrMoveBox(objectsender,EventArgse){if(pnlBox.Location.X<=316){for(inti=0;i=0){for(inti=0;i>=316;i++){pnlBox.Location=newPoint(pnlBox.Location.X-2、pnlBox.Location.Y);字符串BoxLocationToString=pnlBox.Location.ToString();lblXY.Text=BoxLocationToString;}}}第二个最好的尝试:privatevoidtmrMoveBox(objectsender,EventArgse){intrunBox=1;if(runBox==1){while(pnlBox.Location.X0){pnlBox.Location=newPoint(pnlBox.Location.X-2,pnlBox.Location.Y);字符串BoxLocationString=pnlBox.Location.ToString();lblXY.Text=BoxLocationString;运行框=1;}}}尝试使用while循环,但面板就消失了。我不是专家,只是把这个移动面板作为我自己的目标。希望有人能给我提示。编辑:Form1.Designer.csthis.timer1.Interval=50;this.timer1.Tick+=newSystem.EventHandler(this.tmrMoveBox);这个.timer1.Start();这个.timer1.Step=2;创建一个计时器并订阅Tick事件。同时创建新的int属性Step。System.Windows.Forms.Timert=newSystem.Windows.Forms.Timer();内部步骤;Form1(){InitializeComponent()....t.Interval=15000;//根据需要指定间隔时间t.Tick+=newEventHandler(timer_Tick);t.开始();这一步=2;}并将您的逻辑放在ticks事件处理程序中,而不是voidtimer_Tick(objectsender,EventArgse){if(pnlBox.Location.X>=316){Step=-2;}if(pnlBox.Location.X所以每次计时器滴答时你的盒子都会走一步。这是我使用的代码:intd=10;privatevoidtimer1_Tick(objectsender,EventArgse){//碰撞后反转移动方向if(panel1.Left==0||panel1.Right==this.ClientRectangle.Width)d=-d;//移动panel,也防止它超出borderseventapoint。if(d>0)panel1.Left=Math.Min(panel1.Left+d,this.ClientRectangle.Width-panel1.Width);elsepanel1.Left=Math.Max(panel1.Left+d,0);注意:要检查碰撞你应该检查:你不应该让面板超出边界哪怕一点点,所以:最好使用this.ClientRectangle.Width而不是硬编码316。以上是C#学习教程:C#面板随碰撞而动,分享所有内容。如果对你有用,需要进一步了解C#学习教程,希望大家多加关注---本文收集自网络,不代表立场,如涉及侵权,请指教点击右侧联系管理员删除。如需转载请注明出处:
