Creating smooth lighting transitions using tiles in HTML5/JavaScript game
Posted
by
user12098
on Game Development
See other posts from Game Development
or by user12098
Published on 2012-03-27T10:35:19Z
Indexed on
2012/03/27
11:41 UTC
Read the original article
Hit count: 290
JavaScript
|lighting
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:
- 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.
- 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.
- I am then spawning a transparent 40 x 40px "grid block" entity at each position in the array
- The engine I'm using (ImpactJS) then allows me to calculate the distance from my light source entity to every instance of this grid block entity.
- I can then replace the tile underneath each of those grid block tiles with a tile of the appropriate transparency.
Currently I'm doing the calculation like this in each instance of the grid block entity that is spawned on the map:
var dist = this.distanceTo( ig.game.player );
var percentage = 100 * dist / 960;
if (percentage < 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 < 4) {
ig.game.backgroundMaps[2].setTile( this.pos.x, this.pos.y, 63 );
}
else if (percentage < 6) {
ig.game.backgroundMaps[2].setTile( this.pos.x, this.pos.y, 62 );
}
// etc...
(sorry about the weird spacing, I still haven't gotten the hang of pasting code in here properly)
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 forumla 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?
(PS: I'm reposting this from Stack Overflow at someone's suggestion, sorry about the duplicate!)
© Game Development or respective owner