简体   繁体   中英

Battle Game - How to make direction of firing missile

This is related to the first question that I asked about making infinite missile

Now what I wanted to do now is when my Main Tank changes direction, let's say it turns right. Supposedly when it fires it will travel to the side where the Tank is facing. I can't figure it out much since like it was coded on a Timer.

  private void ShootMissile()
    {

        var missile = new PictureBox();
        this.Controls.Add(missile);
        missile.Width = 10;
        missile.Height = 10;
        missile.BackColor = Color.Black;

        missile.Top = MainTank.Top + MainTank.Height / 2 - missile.Height / 2;
        missile.Left = MainTank.Left + MainTank.Width / 2 - missile.Width / 2;

        missile.BringToFront();

        missiles.Add(missile);

    }
       private void shootingTimer_Tick(object sender, EventArgs e)
    {

        foreach(var missile in missiles)
        {
                missile.Top -= 5;
        }
    }

This works for any angle. If your tank can only rotate in increments of 90º, angles would be 0 for right, 90º for up, 180º for left and 270º for down.

Depending on the orientation of your tank sprite, you may need to add an offset to the forward direction.

var tankForwardDir = 0; 
var radians = tankForwardDir * 3.14159f/180;

var t = 10; // distance to move the missile. 

var dx = Math.Cos(radians)*t;
var dy = Math.Sin(radians)*t;

missile.Top += dy;
missile.Left += dx;

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