我如何让标签在碰到墙壁时改变方向
本文关键字:改变方向 标签 | 更新日期: 2023-09-27 18:01:38
我有一个小问题,我想创建一个标签,慢慢地移动到墙上,当撞到墙上时,它应该返回到另一面墙。我使标签向左走,但过了一段时间,它将通过形式和消失,是可能的,使它向右转(其他方向),当它击中的形式?所以它从一面墙到另一面墙?
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
label1.Left = label1.Left + 10;
}
你必须知道你有可用的宽度和标签文本的宽度,然后你可以创建一个条件,说当currentPosition + labelWidth >= availableWidth
然后移动到另一个方向。当然,屏幕左侧也会出现类似的情况。
我的建议:
private int velocity = 10;
private void timer1_Tick(object sender, EventArgs e)
{
if (currentWidth + labelWidth >= availableWidth)
{
//set velocity to move left
velocity = -10;
}
else if (currentWidth - labelWidth <= 0)
{
//set velocity to move right
velocity = 10;
}
label1.Left = label1.Left + velocity;
}
Sounds like homework to me... just in case it isn't:
private int direction = 1;
private int speed = 10;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
direction = 1;
timer1.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
if( label1.Left + label1.Width > this.Width && direction == 1 ){
direction = -1;
}
if( label1.Left <= 0 && direction == -1 ){
direction = 1;
}
label1.Left = label1.Left + (direction * speed);
}