Reputation: 496
I am making a tile-based game and am implementing lighting. Lighting is done on a per-tile basis, where the intensity of light will be a default value unless it is near a light source. Before I update the lighting, I go through the array of tiles and check if one is a light in something like this:
for(var y=this.x;y<(this.x+this.h);y++){
for(var x=this.y;x<(this.y+this.w);x++){
if(x>=0 && x<earth.plot.length && y>=0 && y<earth.plot.length){
if(earth.plot[y][x].top==13){
this.lights.push(new entity(x,y,this.baseintenseity/5));//adds new light source to the lights array with very bright intensity
}
}
}
}
What would be the best way to go about adding more light values around the light source in a radial pattern, with declining light intensity? Making a simple T pattern was easy, I just added a for loop under the part where I add the light. That looked like this:
var ln=5;
for(var i=0;i<ln;i++){
this.lights.push(new entity(x+(1+i),y,this.baseintenseity/(ln-i)));
this.lights.push(new entity(x-(1+i),y,this.baseintenseity/(ln-i)));
this.lights.push(new entity(x,y-(1+i),this.baseintenseity/(ln-i)));
this.lights.push(new entity(x,y+(1+i),this.baseintenseity/(ln-i)));
}
I'm really just looking for a way to quickly turn the above into a radial pattern around the light source. with decreasing intensity.
Upvotes: 2
Views: 198
Reputation: 496
Figured it out, I had to do a flood fill method.
var lights=[[0,0,0,0,0]
,[0,0,0,0,0]
,[0,0,0,0,0]
,[0,0,0,0,0]
,[0,0,0,0,0]
];
var tiles=[[0,0,0,0,0]
,[0,0,0,0,0]
,[0,0,0,0,0]
,[0,0,0,0,0]
,[0,0,0,0,0]
];
var dx=[0,1,0,-1];
var dy=[-1,0,1,0];
function setlights(x,y,b,dir){
if(b<=0)
return;
tiles[x][y]=1;
lights[x][y]=b;
for(var i=0;i<4;i++){
if (i == dir) {
continue;
}
var newx=x+dx[i];
var newy=y+dy[i];
var newdir = dir;
if (newdir == -1) {
newdir = (i+2)%4;
}
if(newx >= 0 && newx < tiles[0].length && newy >= 0 && newy < tiles.length){
if (!tiles[newx][newy]) {
setlights(newx, newy, b-1, newdir);
}
}
}
}
This fills the variable lights with numbers of intensity, which I then turn into the intensity I want. Calling setlights(2,2,4,-1)
does the trick and returns
01210
12321
23432
12321
01210
Upvotes: 1