Skip to content

Instantly share code, notes, and snippets.

@slashman
Created August 10, 2018 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slashman/7e0bc4c86e746622d0f9230991fe8e2e to your computer and use it in GitHub Desktop.
Save slashman/7e0bc4c86e746622d0f9230991fe8e2e to your computer and use it in GitHub Desktop.
Add torch-like effect to JSRL game
var LIGHT_COLOR = { r: 255, g: 128, b: 128 };
var LIGHT_INTENSITY = 0.7;
var MAX_DIST = 8;
// Helper function that calculates a distance
function distance(x1, y1, x2, y2) {
return Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
}
// Helper function that does blending between two values
function blend(a, b, f) {
return a*f + b*(1.0-f);
}
module.exports = {
init: function(game, config){
// Stripped init
// Shades the tile according to distance from player,
// giving a kind of torch effect
var theGame = this.game;
function doLighting(tile, x, y, time) {
// console.log("TIME", time)
var pl;
try {
pl = theGame.world.level.player;
} catch (e) {
return tile;
}
var xr = x - pl.x;
var yr = y - pl.y;
if (!pl.canSee(xr, yr) || (xr === 0 && yr === 0)){
return tile;
}
// Calculate a pulsating animation value from the time
var anim = time / 1000.0;
anim = Math.abs(anim - Math.floor(anim) - 0.5) + 0.5;
var d = distance(pl.x, pl.y, x, y);
// No shading if the tile is too far away from the player's "torch"
if (d >= MAX_DIST) return tile;
// We will create a new instance of ut.Tile because the tile
// passed in might be (and in this case is) a reference to
// a shared "constant" tile and we don't want the shader to
// affect all the places where that might be referenced
var shaded = new ut.Tile(tile.getChar());
// Calculate a blending factor between light and tile colors
var f = (1.0 - (d / MAX_DIST)) * LIGHT_INTENSITY * anim;
// Do the blending
shaded.r = Math.round(blend(LIGHT_COLOR.r, tile.r, f));
shaded.g = Math.round(blend(LIGHT_COLOR.g, tile.g, f));
shaded.b = Math.round(blend(LIGHT_COLOR.b, tile.b, f));
return shaded;
}
this.eng.setShaderFunc(doLighting);
var that = this;
window.setInterval(function() { that.refresh(); }, 50); // Animation
}
}
@slashman
Copy link
Author

This integrates the torch-like shader from unicodetiles.js https://github.com/tapio/unicodetiles.js into the Display object of JSRL https://github.com/slashman/jsrl

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment