- Home /
Check that the joystick is being pressed for a few seconds
I have a joystick that plays two animations, one when pressed/dragged and one at the time of releasing it, does its job, but halfway, it only looks good if the joystick is pressed for several seconds, however if one quickly presses the joystick the animation when you stop pressing the joystick plays, generating an animation error. The animation plays earlier than it should.
So I would like to make the joystick able to check that it is being pressed for a few seconds to authorize the animation to run. Is there any way to do this? Thank you in advance.
Answer by Llama_w_2Ls · Jan 31, 2021 at 10:42 AM
You could start a timer in the Update, for example (pseudocode ahead):
float time = 0f;
void Update()
{
if (JoystickIsPressed)
{
CheckJoystickPress(3);
}
if (JoystickIsLetGo)
{
if (time >= maxTime)
{
// Joystick was held for more than 3 seconds
PlayAnimation();
time = 0;
}
}
}
void CheckJoystickPress(float maxTime)
{
if (time < maxTime)
{
time += Time.deltaTime;
}
}
I tried to adapt the script to my case, it does not present any errors, however I have not been able to get it to work. I guess I'm ignoring something that needs to be done.
float time = 0f;
private float maxTime = 5f;
private EventTriggerExample eventtt;
public Animator anim;
void Start()
{
anim = GetComponent<Animator>();
}
void Update()
{
if (eventtt)
{
CheckJoystickPress(3);
}
if (eventtt)
{
if (time >= maxTime)
{
// Joystick was held for more than 3 seconds
anim.Play("Layer.DejarDeCorrer");
time = 0;
}
}
}
void CheckJoystickPress(float maxTime)
{
if (time < maxTime)
{
time += Time.deltaTime;
}
}
}
You have the same event trigger for both if statements in the Update. It's better to just put it into one if statement:
if (eventtt)
{
CheckJoystickPress(3);
if (time >= maxTime)
{
// Joystick was held for more than 3 seconds
anim.Play("Layer.DejarDeCorrer");
time = 0;
}
}
Also, the variable maxTime, only exists inside the method CheckJoystickPress(). You should have a private variable at the top called float maxTime;
and set it to maxTime in the method CheckJoystickPress(). $$anonymous$$y bad. @Ezequiel75