如何在C#中将图片框从点逐渐移至光标?

时间:2019-04-10 06:18:05

标签: c# picturebox trigonometry point atan2

我目前正在为学校项目开发C#游戏。我想要在程序中执行的操作是能够从角色精灵中拍摄出一个图片框,并使该图片框逐渐向光标移动。

我已经在线搜索并尝试将此(https://www.codeproject.com/Questions/1155766/Move-a-picturebox-along-a-line)代码应用于我的项目。我的镜头确实相对于光标位置移动,但根本不向光标移动。我已经尝试调整代码很多天了,似乎没有任何效果或对其进行改进。

        Point end;
        Point start;
        int interval = 7;
        Point middle;
        double radians;
        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));

            pictureBox2.Location = middle; //picturebox2 is the shot sprite
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData = Keys.Space)
            {
            start = pictureBox1.Location;
            end = Cursor.Position;
            middle = start;

            radians = (Angle(start, end) - 180) * -1;

            timer1.Enabled = true;
            }
        }

        private void MainGame_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Space)
            {
                timer1.Stop();
                pictureBox2.Location = start;
            }
        }

        const double Rad2Deg = 180.0 / Math.PI;

        private double Angle(Point start, Point end)
        {
            return Math.Atan2(start.Y - end.Y, start.X - end.X) * Rad2Deg;
        }

/*As I stated earlier, the shot doesn't follow my cursor and seems inconsistent in spite of what I try to fix it. */

0 个答案:

没有答案