How to add a timer to say wait for 5 s from now if bools are true?
Hi, I am trying to add an animation to my player if he stays still for 10 seconds. But I have no Idea how to do it.. my initial idea was this: (picture) With IsPlayerMoving() in Update, but this happens whenever the player stops i need to add something lik "If bool !playerIsMovingOnX and !playerIsMovingOnY for 10 seconds"{invoke("StartWawing");. Spent the whole day trying to figure this out on my own but sadly wasnt able to. I am really new to coding so I dont know a lot.
EDIT: added code in picture
Answer by Hellium · Nov 01, 2021 at 09:57 PM
Code not tested
float stillStartTime = -1;
bool isWaving;
void IsPlayerMoving()
{
bool playerIsMovingOnX = myRigidBody.velocity.x > Mathf.Epsilon;
bool playerIsMovingOnY = myRigidBody.velocity.y > Mathf.Epsilon;
// Player is moving, reset the "timer"
if(playerIsMovingOnX || playerIsMovingOnyY)
{
stillStartTime = -1;
isWaving = false;
}
else
{
// Player has stopped moving, start the timer by saving the time it's started being unmoving
if(stillStartTime < 0)
{
stillStartTime = Time.time;
}
// If timer has not been reset (i.e reset to -1), check how long it stayed unmoving
// If it's more than 10 seconds and the object is not already waving, set the trigger
else if(Time.time > stillStartTime + 10 && !isWaving)
{
isWaving = true;
myAnimator.SetTrigger("isWaving");
}
}
}
Next time, please, provide your code as text.
Thank you for answering I just have two questions.. what is lastMovementTime? In the code it says its error. And in the first if statement: if(playerIsMovingOnX || playerIsMovingOnY), shouldnt there be isWaving = false; ? And I am sorry for the code but when i put it as a text all the lines got mushed together even tho i entered it using the enter code function. Thank you for the help I really appreciate it!
My bad, I went with lastMovementTime
first before rena$$anonymous$$g it stillStartTime
.
And yes, isWaving
should be set to false in that condition.
I've fixed the code in my answer.
You can format code using the 101010 button after pasting and selecting it.
Thank you very much! You really helped me thanks for explaining it now i finally understand how Time.time works. Have a fabulous day!
Your answer
![](https://koobas.hobune.stream/wayback/20220613044858im_/https://answers.unity.com/themes/thub/images/avi.jpg)