Click here to Skip to main content
15,896,539 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I want to move a picturebox along a line with timer. I have 2 point as start point and end point. The below code moves the picturebox but dont move along my line:

What I have tried:

C#
<pre lang="C#">Point _start;
        Point _end;
        int _interval = 7;
        Point _middle;
        double radians;
        private void timer1_Tick(object sender, EventArgs e)
        {
            _middle.X -= Convert.ToInt16(_interval * Math.Cos(radians));
            _middle.Y -= Convert.ToInt16(_interval * Math.Sin(radians));

            pictureBox1.Location = _middle;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            _start = pictureBox1.Location;
            _end = new Point(50, 50);
            _middle = _start;

            radians = (Angle(_start, _end) - 180) * -1;

            timer1.Enabled = true;
        }

        const double Rad2Deg = 180.0 / Math.PI;

        private double Angle(Point start, Point end)
        {
            return Math.Atan2(start.Y - end.Y, end.X - start.X) * Rad2Deg;
        }</pre>
Posted
Updated 14-Nov-16 0:19am
Comments
Ralf Meier 14-Nov-16 3:44am    
And how does it move ?
And how should it move ?
You should be more specific ...
maysamfth 14-Nov-16 4:13am    
I said that I want move a picturebox along a straight line but my code move the picturebox along another line. suppose a picturebox initial location is (200,200) then I want move this picturebox to point (50, 50). if you test my code the problem is specify.

1 solution

you should calculate the distances/angles in the right way :
C#
private void timer1_Tick(object sender, EventArgs e)
 {
      _middle.X -= Convert.ToInt16(_interval * Math.Cos(radians / Rad2Deg));
    _middle.Y -= Convert.ToInt16(_interval * Math.Sin(radians / Rad2Deg));

    pictureBox1.Location = _middle;
  }


Cos, Sin and so on are working with radians and not with degrees ...
 
Share this answer
 
Comments
maysamfth 14-Nov-16 7:11am    
thanks.
Ralf Meier 14-Nov-16 8:12am    
you are welcome ... :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900