2

我有一个小问题,我想创建一个缓慢移动到墙上的标签,当撞到墙壁时它应该返回到另一面墙上。我让标签向左走,但过了一会儿它会穿过表格并消失,当它碰到表格时是否可以让它向右转(另一个方向)?所以它从一堵墙到另一堵墙?

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

2 回答 2

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);
}
于 2013-03-01T11:54:20.390 回答
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;

}
于 2013-03-01T11:48:39.670 回答