scriptaculous
scriptaculous copied to clipboard
Add bounce effect to Effect.Transitions
To simulate an object under constant force (e.g. gravity) hitting a surface with a constant coefficient of restitution. The function I've defined below is a function generating function, which takes two parameters: the number of bounces and the coefficient of restitution (called "decay"). A number of pre-calculations are performed to improve the performance of the actual transition function.
bounce: function(bounces, decay) {
// default values
if(decay == null) decay = 1/3;
if(bounces == null) bounces = 2;
// solve geometric series to calculate speed
var rootd = Math.sqrt(decay);
var rootdn = Math.sqrt(Math.pow(decay, bounces));
var f = Math.pow((1 + rootd - (2 * rootdn)) / (1 - rootd), 2);
// pre-calculate offsets
var offsets = [];
var offset = 0;
var apex = 1;
for(var b = 0; b < bounces; b++) {
offsets.push(offset)
offset += Math.sqrt(apex / f);
apex *= decay;
offset += Math.sqrt(apex / f);
}
// generate the bounce function
return (function (pos) {
var h = 0;
var apex = 1;
for(var b = 0; b < bounces; b++) {
h = Math.max(h, apex - (f * Math.pow(pos - offsets[b], 2)));
apex *= decay;
}
return 1 - h;
});
},
Usage: transition: Effect.Transitions.bounce() // use default values of 5, 1/3 or transition: Effect.Transitions.bounce(3) // 3 bounces, default decay (1/3) or transition: Effect.Transitions.bounce(4, 1/2) // 4 bounces, decay 1/2
Sweet stuff. I'll add that in scripty2.