0

I'm currently working on making a game in C# for a school project. What I want to be able to do in the program is to be able to shoot a picturebox out of my character sprite and to get that picturebox to travel toward the cursor gradually.

I've searched online and tried to apply this (https://www.codeproject.com/Questions/1155766/Move-a-picturebox-along-a-line) code to my project. My shot does move in relation to the cursor position but it simply does not move toward the cursor. I've tried adjusting the code for many days now and nothing seems to work or improve it.

        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. */
jallebuS
  • 1
  • 1
  • 1
    how do you want to react if the mouse moves away from the item? should it keep chasing the cursor around? Also, this is WinForms right? not WPF? – Denis Schaf Apr 10 '19 at 06:28
  • this thread should help you: https://stackoverflow.com/questions/6102241/how-can-i-add-moving-effects-to-my-controls-in-c – Denis Schaf Apr 10 '19 at 06:31
  • I only want the picturebox to move toward the position the cursor was at the time the spacebar was pressed. It's not meant to chase after the cursor as you move it around whilst the shot is being fired. And yes, this is WinForms. – jallebuS Apr 10 '19 at 07:25
  • in this case, the link provided above should help you solve your issue :) – Denis Schaf Apr 10 '19 at 07:26
  • Do yourself a favor and use float for coordinates and speed until actually setting the location.. – TaW Apr 10 '19 at 07:59

0 Answers0