Created
September 23, 2020 09:48
-
-
Save Sheepolution/5e2d332e7031ece2901f95f3a31a4c85 to your computer and use it in GitHub Desktop.
Class to use with HaxeFlixel for creating lighting by masks.
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; | |
class Darkness extends FlxBasic { | |
private var darkCamera:FlxCamera; | |
private var maskCamera:FlxCamera; | |
private var maskSprite:FlxSprite; | |
private var maskShader:MaskShader; | |
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.maskCamera = new FlxCamera(); | |
this.maskCamera.bgColor = FlxColor.TRANSPARENT; | |
this.maskCamera.x = FlxG.width; | |
FlxG.cameras.add(this.maskCamera); | |
} | |
override public function update(dt:Float) { | |
this.maskSprite.pixels.fillRect(this.maskSprite.pixels.rect, FlxColor.TRANSPARENT); | |
this.maskSprite.pixels.draw(this.maskCamera.canvas); | |
} | |
public function addLight(light:FlxSprite) { | |
light.camera = this.maskCamera; | |
} | |
} | |
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