简体   繁体   中英

Bullet direction in c#

I am trying to make a game where you have a turret which rotates to mouse position, and on click is firing bullets towards the mouse position. The problem is that using my method (below) doesn't make the bullets go straight, since they can only go in a up, down and 45 degree diagonal direction. Also, I can't figure out a way to make the bullets continue their direction after reaching mouse position. I suspect my whole approach to the problem may be wrong... (as I'm fairly new to c#). Any help would be appreciated, thank you.

private void timer1_Tick(object sender, EventArgs e)
{
 int x = pictureBox1.Location.X;
 int y = pictureBox1.Location.Y;
 if (pictureBox1.Location.X < Cursor.Position.X - pictureBox1.Width / 2)
 {
     x = x + 3;
     pictureBox1.Location = new Point(x, y);
 }

 if (pictureBox1.Location.X > Cursor.Position.X - pictureBox1.Width / 2)
 {
     x = x - 3;
     pictureBox1.Location = new Point(x, y);
 }

if (pictureBox1.Location.Y > Cursor.Position.Y - pictureBox1.Height / 2)
 {
     y = y - 3;
     pictureBox1.Location = new Point(x, y);
 }

if (pictureBox1.Location.Y < Cursor.Position.Y - pictureBox1.Height / 2)
 {
     y = y + 3;
     pictureBox1.Location = new Point(x, y);
 }
}

You can quite easily solve your problem with regards to direction by holding the bullets velocity in an array:

int[] bulletVelocity = {vx, vy};

where vx is the velocity in x direction and likewise vy for y. These will determine how much you change the bullets x and y position at each timer tick.

To make them always fly towards the bullet you will need to register the click position and hold it with the bullet in question. One solution would be to have a Bullet class and have a Point object within which you can set as the mouse click position.

You will also use this Point to set the initial velocity for the bullet, eg x and y will be proportionate to the different in the x and y components of the bullet and the click.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM