Home > Net >  Firing in multiple directions at once. (Unity)
Firing in multiple directions at once. (Unity)

Time:07-14

I'm making a top down shooter game in unity using the old input system and I ran into a problem. I use the arrow keys to shoot but I'm not sure how to fire in multiple directions at the same time/frame. Code:

void Update()
    {
        currentTime  = Time.deltaTime;
        //input section
        if (Input.GetKey(KeyCode.UpArrow))
        {
            ShootUp();
        }

        if (Input.GetKey(KeyCode.DownArrow))
        {
            ShootDown();
        }

        if (Input.GetKey(KeyCode.LeftArrow))
        {
            ShootLeft();
        }

        if (Input.GetKey(KeyCode.RightArrow))
        {
            ShootRight();
        }

        if (Input.GetKey(KeyCode.UpArrow) && Input.GetKey(KeyCode.RightArrow))
        {
            ShootUp();
            ShootRight();
        }

 }

I thought that looking at both arrow keys at the same time, I would just call both functions as well. Its does not work however. I tried google but it's pretty hard to find info on the old input system having the same problem.

CodePudding user response:

The code you wrote works. Basically the code you wrote says this:

If (I pressed the up arrow)
So {
Shoot high;
}

If (I pressed the down arrow)
So {
Shoot down;
}

If (I pressed the left arrow)
So {
Shoot left;
}

If (I pressed the right arrow)
So {
Shoot right;
}

Your code would not have worked if instead of writing 4 if, you had written if only if and 3 else if.

In this case it would mean:

If (I pressed the up arrow)
So {
    shoot high;
}
If the condition was not true before and if (I pressed the down arrow)
So {
    Shoot down;
}
If all the above conditions are not true and If (I pressed the left arrow) ...

So, the only thing you need to change in your code is: delete the last if (it's useless).

Hope I was helpful :)

CodePudding user response:

Okay, so first of all. All of these should go into a seperate method and then called in Update. Secondly, Input.GetAxis use that, and write a method which would take a Vector2 direction and instantiate a bullet towards that direction.


private void Update()
{
   currentTime  = Time.deltaTime;
   Shooting();
}

private void Shooting()
{
   var x = Input.GetAxis("Horizontal");
   var y = Input.GetAxis("Vertical");
   Vector2 direction = new Vector2(x, y);
   
}

private void Shoot(Vector2 direction)
{
   // Instantiate bullets and fire them towards direction.
}

Google Input.GetAxis method, and Vector2 in case you do not know that.

  • Related