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:
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 );
}
(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 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?
var size = 32;
var a = [size];
for (i = 0; i < size; i++) {
a[i] = [size];
for (y = 0; y < size; y++) {
a[i][y] = 1;
}
}
function display(arr) {
h = "";
for (y = 0; y < size; y++) {
for (x = 0; x < size; x++) {
h += "<span style='background-color:rgba(255,255,255," + (arr[x][y] / 10) + ")'></span>";
if (x == size - 1) {
h += "<br/>";
}
}
}
$("#h").html(h);
}
function LightSource(x, y, l) {
this.x = x;
this.y = y;
this.l = l;
}
var ls = [];
ls.push(new LightSource(6, 6, 4));
ls.push(new LightSource(2, 2, 3));
ls.push(new LightSource(9, 9, 5));
ls.push(new LightSource(20, 14, 8));
ls.push(new LightSource(20, 19, 8));
for (z = 0; z < ls.length; z++) {
for (x = 0; x < size; x++) {
for (y = 0; y < size; y++) {
xd = x - ls[z].x;
yd = y - ls[z].y;
dist = Math.sqrt(xd * xd + yd * yd);
if (ls[z].l - dist > 0) {
a[x][y] += ((10 - a[x][y]) / 10) * (ls[z].l - dist);
}
}
}
}
display(a);
https://gamedev.stackexchange.com/questions/23454/grid-cell-based-light-system