Last active
September 23, 2020 15:02
-
-
Save Sheepolution/f08570122a6cb6e9dda798a3c0b20d1e to your computer and use it in GitHub Desktop.
Class to use with HaxeFlixel for creating lighting by masks. This advanced version allows the use of alpha, but is very slow.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import flixel.FlxBasic; | |
import flixel.FlxCamera; | |
import flixel.FlxG; | |
import flixel.FlxSprite; | |
import flixel.system.FlxAssets.FlxShader; | |
import flixel.util.FlxColor; | |
import openfl.display.BlendMode; | |
import openfl.filters.ShaderFilter; | |
import openfl.geom.Matrix; | |
class Darkness extends FlxBasic { | |
private var darkCamera:FlxCamera; | |
private var maskSprite:FlxSprite; | |
private var maskShader:MaskShader; | |
private var lights:Array<FlxSprite>; | |
public function new() { | |
super(); | |
this.maskSprite = new FlxSprite(0, 0); | |
this.maskSprite.makeGraphic(FlxG.width, FlxG.height, FlxColor.TRANSPARENT, true); | |
this.maskSprite.blend = BlendMode.ALPHA; | |
this.maskShader = new MaskShader(); | |
this.maskShader.tex.input = this.maskSprite.pixels; | |
this.darkCamera = new FlxCamera(); | |
this.darkCamera.bgColor = FlxColor.BLACK; | |
this.darkCamera.setFilters([new ShaderFilter(this.maskShader)]); | |
FlxG.cameras.add(this.darkCamera); | |
this.lights = new Array<FlxSprite>(); | |
} | |
override public function draw() { | |
this.maskSprite.pixels.fillRect(this.maskSprite.pixels.rect, FlxColor.TRANSPARENT); | |
for (sprite in lights) { | |
this.maskSprite.pixels.draw(sprite.pixels, new Matrix(1, 0, 0, 1, sprite.x, sprite.y), sprite.colorTransform, sprite.blend); | |
} | |
} | |
public function addLight(light:FlxSprite) { | |
this.lights.push(light); | |
} | |
} | |
class MaskShader extends FlxShader { | |
@:glFragmentSource(' | |
#pragma header | |
uniform sampler2D tex; | |
void main() | |
{ | |
vec4 source = flixel_texture2D(bitmap, openfl_TextureCoordv); | |
vec4 mask = flixel_texture2D(tex, openfl_TextureCoordv); | |
source.a *= 1.0 - mask.a; | |
gl_FragColor = source; | |
} | |
') | |
public function new() { | |
super(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment