Calculate index

I have vector of keyframes for animation:
1
2
3
4
5
6
7
struct Keyframe
{
    float time;// time in seconds
    ...
};

std::vector<Keyframe> vKeys;


and every loop i accumulate delta time to animate my object:
1
2
3
4
5
6
update(float deltaTime)
{
    timeRunning += deltaTime;
    
    const float animationLen = 5.0f; // 5 seconds is total length of animation
...


to calculate current Key/index into vector i use:
1
2
3
4
float currTime = std::fmod(timeRunning, animationLen);
m_currKeyFrameInx = std::size_t(vKeys.size() * currTime / animationLen);

... use index


Can this logic fail?

edit:
Before i was using this:
1
2
3
4
5
6
7
8
9
10
float currTime = std::fmod(timeRunning, animationLen);
m_currKeyFrameInx = 0u;
	for (std::size_t i = vKeys.size(); --i;)
	{
		if (vKeys[i].time < currTime)
		{
			m_currKeyFrameInx = i;
			break;
		}
	}
Last edited on
Can this logic fail?
I can't see why it should work.

The problem with your code is that it assumes that the frames are spaced exactly the same amount of time apart, it doesn't account for significant variance that can occur when capturing real data. Of course, if you're generating frames, there is some guarantee this might not be the case.

I assume the frame you want is the latest frame that is before the timestamp. If your times were held as struct timeval (an integral type) rather than float, you could use standard algorithms to do the search for you.
The keys are evenly (time) spaced, yes i made those animations/keys.


I assume the frame you want is the latest frame that is before the timestamp

yes.
I think your method should be ok. It would help if you were able to it, but the O(1) algorithm will be much better than that O(n) one you had before.
Topic archived. No new replies allowed.