Last active
December 29, 2015 08:59
-
-
Save godDLL/7647338 to your computer and use it in GitHub Desktop.
Schedule a function to run as often as possible, featuring a difference_in_time from the last time it ran, an adjustable clock_with_velocity for bullet time, and a frame counter with which you can build your own FPS meter.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function (win, undefined){ | |
// Schedule a function to run as often as possible, | |
// featuring a difference_in_time from the last time it ran, | |
// an adjustable clock_with_velocity for bullet time, | |
// and a frame counter with which you can build your own FPS meter. | |
var gettime = function (){ | |
return (new Date).getTime() | |
}, | |
animate = (function(){ // animate(fn, starting_velocity) | |
// fn( | |
// dt, | |
// frame = Timeline.pos, | |
// Timeline = {time(), last_t, pos, vel} | |
// ) | |
function Timeline(vel, pos){ | |
this.last_t = gettime(), | |
this.vel = vel || 1, | |
this.pos = pos || 0 | |
this.time = function (num){ | |
// quantum time measurement, disturbs the time | |
if (num) this.pos = num | |
var t = this.last_t | |
this.last_t = gettime(), | |
this.pos = this.pos + this.vel * (this.last_t - t) | |
return this.last_t | |
} | |
} | |
return function(fn, vel){ | |
// teh interface | |
var run = true, last_t, clock = new Timeline(vel), | |
Loop = function (t){ | |
// needs requestAnimationFrame polyfill | |
if (run) window.requestAnimationFrame(Loop) | |
else return | |
last_t = clock.last_t || clock.time() | |
t = clock.time() // starts at 'frame 1' because | |
var dt = clock.vel * Math.abs(t - last_t) | |
run = fn(dt, clock, clock.pos) | |
dt = null | |
} | |
Loop() | |
} | |
})() | |
win.animate = animate | |
})(window) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// USAGE example | |
animate(function(dt, t, frame){ | |
// this is playing with the clock speed, ignore | |
if (t.set_vel === void 0) | |
t.set_vel = t.vel = t.vel * 2 | |
if (frame > 200 && t.unset_vel === void 0) | |
t.unset_vel = t.vel = t.vel / 2 | |
// why do I even import undefined if I never end up using it? | |
console.log(t.last_t, dt, | |
frame, t.vel) // frame == t.pos | |
if (frame < 300) | |
return true // stop animation at frame 300 | |
}, .5) // starting at half speed | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment