title: Creating smooth lighting transitions using tiles in HTML5/JavaScript game
body: <p>I am trying to implement a lighting effect in an HTML5/JavaScript game using tile replacement. What I have now is kind of working, but the transitions do not look smooth/natural enough as the light source moves around. Here's where I am now:</p>
  
  <ol>
  <li>Right now I have a background map that has a light/shadow spectrum PNG tilesheet applied to it - going from darkest tile to completely transparent. By default the darkest tile is drawn across the entire level on launch, covering all other layers etc. </li>
  
  <li>I am using my predetermined tile sizes (40 x 40px) to calculate the position of each tile and store its x and y coordinates in an array.</li> 
  
  <li>I am then spawning a transparent 40 x 40px "grid block" entity at each position in the array</li>
  
  <li>The engine I'm using ([ImpactJS][1]) then allows me to calculate the distance from my light source entity to every instance of this grid block entity.</li>
  
  <li>I can then replace the tile underneath each of those grid block tiles with a tile of the appropriate transparency.</li></ol> 
  
  <p>Currently I'm doing the calculation like this in each instance of the grid block entity that is spawned on the map:</p>
  
  <pre><code>var dist = this.distanceTo( ig.game.player );
  
  var percentage = 100 * dist / 960;
  
  if (percentage &lt; 2) {
      // Spawns tile 64 of the shadow spectrum tilesheet at the specified position
      ig.game.backgroundMaps[2].setTile( this.pos.x, this.pos.y, 64 ); 
  } else if (percentage &lt; 4) {
      ig.game.backgroundMaps[2].setTile( this.pos.x, this.pos.y, 63 );
  } else if (percentage &lt; 6) {
      ig.game.backgroundMaps[2].setTile( this.pos.x, this.pos.y, 62 );
  }       
  </code></pre>
  
  <p>(sorry about the weird spacing, I still haven't gotten the hang of pasting code in here properly)</p>
  
  <p>The problem is that like I said, this type of calculation does not make the light source look very natural. Tile switching looks too sharp whereas ideally they would fade in and out smoothly using the spectrum tilesheet (I copied the tilesheet from another game that manages to do this, so I know it's not a problem with the tile shades. I'm just not sure how the other game is doing it). I'm thinking that perhaps my method of using percentages to switch out tiles could be replaced with a better/more dynamic proximity formula of some sort that would allow for smoother transitions? Might anyone have any ideas for what I can do to improve the visuals here, or a better way of calculating proximity with the information I'm collecting about each tile?</p>