Skip to content

Instantly share code, notes, and snippets.

@ZaidaZadkiel
Last active December 11, 2020 14:52
Show Gist options
  • Save ZaidaZadkiel/938688b835f14333db4f8f9df9d57712 to your computer and use it in GitHub Desktop.
Save ZaidaZadkiel/938688b835f14333db4f8f9df9d57712 to your computer and use it in GitHub Desktop.
package com.ZaidaZadkiel.ValueTime;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.math.Interpolation;
public class ValueTime {
public float values[];
public float times[];
public int lastindex=0;
public float time = 0.0f;
private float totalTime = 0f;
// vt.times = new float[3];
// vt.times[0] = 1;
// vt.times[1] = 2;
// vt.times[2] = 0;
//
// vt.values = new float[3];
// vt.values[0] = 123;
// vt.values[1] = 321;
// vt.values[2] = 200;
public float length(){
if(totalTime==0) //bad cache, should flag on value insert
for(int i =0; i!= times.length; i++){
totalTime+=times[i];
}
return totalTime;
}
//this can be fixed, the only reason acc is public is for debug
float acc = 0;
public float get(){
if(values.length==1) return values[0];
//this can be fixed, the only reason acc is public is for debug
acc = 0;
for(lastindex=0; lastindex<times.length; lastindex++) {
acc += times[lastindex];
if(acc > time) break;
}
//get a value 0..1 between values[current] to values[current+1]
// time determines how much to interpolate between times[n] and times[n+1]
// when time == times[n], the result is values[n]
// when time == times[n+1] the result is values[n+1]
float alpha = (
lastindex==times.length-1
? normalize(time, acc-times[lastindex], length() ) //last frame goes back to first frame
: normalize(time, lastindex>0 ? times[lastindex-1] : 0, acc)
// : normalize(time, lastindex>0 ? times[lastindex-1] : 0, times[lastindex])
); //current frame goes to next frame
//this version does looping from the last frame to the first frame
return lastindex==values.length-1
? values[lastindex] + (values[0]-values[lastindex])*alpha
: values[lastindex] + (values[lastindex+1]-values[lastindex])*alpha;
//animates and stays still on the last frame for the duration of the frame
// return lastindex==values.length-1 ? values[lastindex] :
// values[lastindex] + (values[lastindex+1]-values[lastindex])*alpha;
}
/**
* Calculates a value between 0 and 1, when the value exceeds in either side, it returns 0 or 1
* 0 means value = min, and 1 means value = max.
*/
float normalize(float value, float min, float max) {
return value<min ? 0 : value>max ? 1 :
( ((value - min) / (max - min)));
}
public float timeAbs(float time){
return this.time=time;
}
public float timeDelta(float delta){
return time+=delta;
}
public float timeLoop(float delta){
return time= (time+delta) % length();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment