- Home /
Getting Input.GetAxis to Execute Once
I wanna have Input.GetAxis
to act like regular button (e.g. Input.GetButtonUp
).
As I'm using the GetAxis, everytime I shift the stick to one direction, the command inside the function is executed more than once, only need it to be executed once. Here's my code. Anyway I can remedy this?
if ( Input.GetAxis("RightStickX") == 1 )
{
SwitchTarget();
}
Answer by Randize · Dec 26, 2013 at 03:20 PM
I've found a way moments later after I posted this, here's what I did to resolve my own problem. GetAxisRaw returns only 0 or 1/-1, it just doesn't have the GetButtonUp function, so had to be resolved with a condition check, in this case using boolean axisInUse. Thanks for taking the time to help, appreciate it.
private bool axisInUse = false;
if (Input.GetAxisRaw("RightStickX") == 1)
{
if (axisInUse == false)
{
axisInUse = true;
SwitchTarget();
Debug.Log ("+1 Switch!");
}
}
else if (Input.GetAxisRaw("RightStickX") == -1)
{
if (axisInUse == false)
{
axisInUse = true;
SwitchTarget();
Debug.Log ("-1 Switch!");
}
}
Answer by bilo-lwabona · Dec 26, 2013 at 12:18 PM
What you could do is use a Coroutine to allow a cooldown of X seconds before you switch to the next target. For example:
public bool canSwitchTarget = true;
public float coolDownUntilNextSwitch = 1.0f;
public void Controls()
{
...
if(Input.GetAxis("RightStickX") == 1 )
{
StartCoroutine(SwitchTargetRoutine(coolDownUntilNextSwitch));
}
}
IEnumerator SwitchTargetRoutine(float duration)
{
if(canSwitchTarget)
{
canSwitchTarget = false;
SwitchTarget();
yield return new WaitForSeconds( duration );
canSwitchTarget = true;
}
else
{
yield return new WaitForSeconds( 0f );
}
}
public void SwitchTarget()
{
// your functions logic to switch targets
}
Hope this helps. Haven't actually tested the code...
Cheers
Bilo
Note: 1. this is C# ... not sure which language you are using 2. I would suggest when checking for the right stick, rather than checking: ( ...axis == 1) I would suggest you check: (...axis >= 0.8f), because some gamepads' sticks might be a bit glitchy/broken that they can't reach the edges, so only go to something like 0.96.
Thanks bilo, I thought of using the cooldown method with coroutine too but later I've found a way using a condition check and GetRawAxis. Thanks for taking the time to answer man, appreciate it.
Answer by astracat111 · Dec 28, 2016 at 10:56 PM
int state;
int cooldown;
if (state == 0) {
var inp_vert = Input.GetAxis ("Vertical");
if (inp_vert != 0) {
cooldown = 60;
state = 1;
}
}
if (state == 1) {
//Do what you need to do
state = 3;
}
if (state == 2) {
cooldown--;
if (cooldown < 1)
state = 0;
}
Your answer
Follow this Question
Related Questions
GameController Unity wrong Axis-Values 0 Answers
Capture Joystick Direction Accurately 2 Answers
Joystick not responding correctly 0 Answers
Joystick Angle Problems 0 Answers
Joystick Input - "3rd Axis" etc, not sure what works/doesn't 1 Answer