Search Unity

Input: Turning GetAxis into a GetButtonDown

Discussion in 'Scripting' started by laurentlavigne, Jul 26, 2017.

  1. laurentlavigne

    laurentlavigne

    Joined:
    Aug 16, 2012
    Posts:
    6,327
    So the bumper buttons on the xbox controller are axis, so if you want to turn them into a "fire" button you need to check the value of the "Fire" axis that the button 6 or 8 are mapped to.

    The traditional way of doing GetButtonDown for axis is to have an Update loop sitting somewhere in your scene. I'd like to minimize the number of manager that my game logic depends on so Is there a way to do that without an Update loop, with events?
     
  2. laurentlavigne

    laurentlavigne

    Joined:
    Aug 16, 2012
    Posts:
    6,327
    Spaghetti code to the rescue.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class InputX
    6. {
    7.     static bool fireDown, firePressed;
    8.     static float timeLastFireDownQuerry, timeLastFireQuerry;
    9.  
    10.     public static bool IsFireButtonDown ()
    11.     {
    12.         if (Time.time == timeLastFireDownQuerry)
    13.         {
    14.             return fireDown;
    15.         }
    16.         else
    17.         {
    18.             timeLastFireDownQuerry = Time.time;
    19.             if (fireDown)
    20.             {
    21.                 fireDown = false;
    22.             }
    23.             else if (Input.GetButton ("Fire") || Input.GetAxis ("Fire") > .1f)
    24.             {
    25.                 fireDown = true;
    26.             }
    27.             return fireDown;
    28.         }
    29.     }
    30.  
    31.     public static bool IsFireButtonPressed ()
    32.     {
    33.         IsFireButtonDown ();
    34.         if (Time.time == timeLastFireQuerry)
    35.         {
    36.             return firePressed;
    37.         }
    38.         else
    39.         {
    40.             timeLastFireQuerry = Time.time;
    41.             firePressed = Input.GetButton ("Fire") || Input.GetAxis ("Fire") > .1f;
    42.             return firePressed;
    43.         }
    44.     }
    45. }
    46.  
     
  3. JohnPet

    JohnPet

    Joined:
    Aug 19, 2012
    Posts:
    85
    Kinda late, but I've found a much faster solution:
    Code (CSharp):
    1.         if(actionPressed)
    2.             actionPressed = false;
    3.         else if(actionAxis > 0f && actionAllow)
    4.         {
    5.             actionPressed = true;
    6.             actionAllow = false;
    7.         }
    8.         if(actionAxis <= 0f)
    9.             actionAllow = true;
    actionAxis is you axis input and actionPressed is the GetButtonDown equivalent.