N
N
Necro98982018-04-26 06:04:16
C++ / C#
Necro9898, 2018-04-26 06:04:16

How to make it so that each if is executed at the same time?

Hello!
I'm working on a game on the Unity engine (2D)
How do I make sure that each if is executed "simultaneously" and not from top to bottom (I know that the code is always executed from top to bottom, but how can I "get around" this)
What I need from the code: If I hold down the DownArrow key and then (for example) the UpArrow key, the FireSphere was created already on the last key pressed
.

if (Input.GetButton("RightArrow") && Time.time > timeToFire)
        {
            timeToFire = Time.time + 1 / fireRate;
            Instantiate(fireSphere, firePoint.position, firePoint.rotation);
        }

        if (Input.GetButton("LeftArrow") && Time.time > timeToFire)
        {
            timeToFire = Time.time + 1 / fireRate;
            Instantiate(fireSphere, firePoint.position, firePoint.rotation);
        }

        if (Input.GetButton("UpArrow") && Time.time > timeToFire)
        {
            timeToFire = Time.time + 1 / fireRate;
            Instantiate(fireSphere, firePoint.position, firePoint.rotation);
        }

        if (Input.GetButton("DownArrow") && Time.time > timeToFire)
        {
            timeToFire = Time.time + 1 / fireRate;
            Instantiate(fireSphere, firePoint.position, firePoint.rotation);
        }

Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Pavlov, 2018-04-26
@Necro9898

Check not individual keys, but combinations:

var isLeftPressed = Input.GetButton("LeftArrow");
var isUpPressed = Input.GetButton("UpArrow");
var isRightPressed = Input.GetButton("RightArrow");
var isDownPressed = Input.GetButton("DownArrow");
if (isUpPressed && isDownPressed && Time.time > timeToFire)
{
    timeToFire = Time.time + 1 / fireRate;
    Instantiate(fireSphere, firePoint.position, firePoint.rotation);
}

F
freeExec, 2018-04-26
@freeExec

You should only have one spawn location.
Those. the train of thought is:

createBall = false
if UP
{
   if beforeDOWN {
      createBall = true
   }
}
if createBall 
{
   Instantiate(...)
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question