- Home /
Timer "overshooting" very small interval check
Hello, all! I'm sorry if this question overlap some already answered ones about deltaTime behavior and framerate dependancy... I've found useful answers but not specifically related to this..
The following code is placed on a sprite and cycles through its animation frames over time.
private float animTimer = 0f;
private float animInterval = 0.03f;
private int displayFrame = 0;
void Update () {
animTimer += Time.deltaTime;
if (animTimer >= animInterval) {
animTimer = 0f;
renderer.material.mainTextureOffset = animMove[displayFrame];
displayFrame += 1;
if (displayFrame == animMove.Length) {
displayFrame = 0;
}
}
}
For example, a 0.1f animInterval solves the problem, but with a 0.03f one, animTimer excess the interval, thus slowing down the animation with slower framerate.
Conversely, if I set the animInterval to a larger number and instead multiply the timer incrementation...
animTimer += Time.deltaTime*3;
if (animTimer >= animInterval) { //0.1f
the opposite happens: the sprite animation is speedier at lower fps.
Well, there is easy solution but I don't know which one to pick up: use FixedUpdate instead (i've tried and it solves it), or code my own global timer or use InvokeRepeating. Which one do you think is the best ? But also it scares me that gameplay related event based on tight timing might be completely biased on different hardware speed..
Thanks for your time,
I guess I'm not really seeing what you're asking here. What exactly is the problem?
well the immediate problem is that sprite animation which are an old-fashioned sequence of sprites, to be smooth, requires very small interval, and they become frame rate dependant as far as I'm concerned, at least using Time.deltaTime in the Update().
So I wonder if it is a known problem what is the best solution. it seems dumb, maybe just using FixedUpdate is fine, but I've always thought it is best to avoid it for anything except physics.
Answer by robertbu · Oct 18, 2013 at 03:46 PM
You have one problem here that might help you get a smoother frame rate. Try changing line 8 to:
animTimer = animTimer - animInterval;
Typically your timer will be over animInterval in the 'if' statement on line 7. By setting animTimer to zero, you don't account for the overlap into the next frame's time.
Your answer
Follow this Question
Related Questions
How would I make a timer frame independent? 1 Answer
How to create a frame indipendent timer 0 Answers
Help with regenerating ammo 2 Answers
Timer that stops at trigger 1 Answer
Loop a function, once per second, X number of times 1 Answer