/* bouncytext.js
Text effect that makes your text bounce.
Feel free to use this in your own games, if you like.

Copyright ©Vincent Beers from Tengudev, 2010
This work by DaVince (Vincent Beers) is licensed under a Creative Commons Attribution-Share Alike 3.0 Unported License.
More information: http://creativecommons.org/licenses/by-sa/3.0/
*/



/** Bouncy text effect. **/
function BouncyText(font, text)
{
  this.font = font;
  this.text = text;
  this.letters = [];
  var on = true;
  
  /** Constructor type method for BouncyText. **/
  this.init = function()
  {
    for (var i = 0; i < this.text.length; i++)
      this.letters[i] = new BouncyLetter(this.text[i], this.font.getStringWidth(this.text.slice(0, i)), 30-i*2);
  }
  this.init();
  
  this.update = function()
  {
		on = !on; //Quick hack to fix the timing in the 60FPS engine
		if (on)
		{
			for (var i = 0; i < this.text.length; i++)
				this.letters[i].update();
		}
  }
  
  this.draw = function(x, y)
  {
    for (var i = 0; i < this.text.length; i++)
      this.font.drawText(x+this.letters[i].x, y+this.letters[i].y, this.letters[i].text);
  }
  
  this.setGravity = function(gravity)
  {
    for (var i = 0; i < this.text.length; i++)
      this.letters[i].gravity = gravity;
  }
}



function BouncyLetter(letter, x, time)
{
  this.text = letter;
  this.x = x;
  this.y = 0;
  this.time = time;
  this.maxtime = 30;
  
  this.jumping = false;
  this.yspeed = 0;
  this.gravity = 0.9;
  
  this.update = function()
  {
    this.time++;
    if (this.time > this.maxtime)
    {
      this.time = -40;
      this.yspeed = -5;
      this.jumping = true;
    }
    
    if (this.jumping)
    {
      this.yspeed += this.gravity;
      this.y += this.yspeed;
    }
    
    if (this.yspeed > 0 && this.y > 0)
    {
      this.yspeed = -this.yspeed+1;
      this.y = 0;
    }
    
    if (Math.floor(this.y) == 0 && Math.floor(this.yspeed) == 0)
      this.jumping = false;
  }
}