- Home /
counting seconds that character is idle.
How do you set a timer on a character to start counting in seconds the amount of time that it has been idle/not moving? Could you please provide a Javascript code example to explain. Thank you for your help.
Answer by aldonaletto · Apr 06, 2012 at 10:03 PM
If it's a CharacterController, it's better to keep track of the movement calculating the distance to the last position each Update:
var idleTimer: float = 0.0; private var lastPos: Vector3;
function Start(){ lastPos = transform.position; }
function Update(){ // calculate the velocity since last Update: var vel: float = Vector3.Distance(transform.position, lastPos)/Time.deltaTime; lastPos = transform.position; // update lastPos if (vel > 0.001){ // if vel slightly greater than zero... idleTimer = 0.0; // reset timer } else { // if zero or too near to zero... idleTimer += Time.deltaTime; // count time in idleTimer } ... }
I thought also if he is using the keyboard, to check if Input returns 1 or 0 and counting how many frame we get 0 with count+=Time.deltaTime