Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add bounce effect to Effect.Transitions #6

Open
edg2s opened this issue Jan 12, 2010 · 1 comment
Open

Add bounce effect to Effect.Transitions #6

edg2s opened this issue Jan 12, 2010 · 1 comment

Comments

@edg2s
Copy link

edg2s commented Jan 12, 2010

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

@madrobby
Copy link
Owner

Sweet stuff. I'll add that in scripty2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants