I'm working on a tile based digger-game in java where i would like to use gradual lighting around the player, think Terraria. I'm currently just overlapping an image with a rectangle where the alpha on that rectangle is the brightness i wish to have (0.01=black, 1=bright), which works OK. It's not how I set the lighting that i need help with, it's how to write a compact and efficient algorithm that gets me a bigger number the closer the block is to the player, and a smaller number the further away the block is from the player. The number should be in the range (1 - 0.01). I call the following method every time the player moves:
public void calculateBlockBrightness(int playerInRow, int playerInCol) {
int affectedBlocks = 5;
float brightness;
// Loops through all blocks within (affectedBlocks) blocks of the player
for (int row = playerInRow - affectedBlocks; row <= playerInRow + affectedBlocks; row++) {
for (int col = playerInCol - affectedBlocks; col <= playerInCol + affectedBlocks; col++) {
// Not all blocks should be affected by this method
if (blockNotRelevantForBrightness(row, col))
continue;
// If the block is within (affectedBlocks - 1) blocks of the player
if (row >= playerInRow - (affectedBlocks - 1) && row <= playerInRow + (affectedBlocks - 1)
&& col >= playerInCol - (affectedBlocks - 1) && col <= playerInCol + (affectedBlocks - 1)) {
/*
* Algorithm
*/
blocks[row][col].setBrightnessPercentage(brightness);
// Reset the "outer layer" blocks to default brightness.
} else {
blocks[row][col].setBrightnessPercentage(blocks[row][col].getBrightnessDefault());
}
}
}
}