我有一个小问题,我想创建一个标签,缓慢移动到墙上,当它撞到墙壁时,它应该返回到另一面墙。我让标签向左移动,但过了一会儿它会通过表格并消失,是否有可能在它撞到表格时向右转(另一个方向)?它是从墙到墙吗?
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;
}
答案 0 :(得分:1)
您必须知道可用的宽度和标签文本的宽度,然后您可以创建一个条件,表示当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;
}
答案 1 :(得分:1)
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);
}