Friday, October 11, 2019

transparency - Make some black pixels transparent in Love2D


Is it possible to put a black opaque rectangle over my game screen and then change transparency on some pixels?


For example I have black rectangle on screen represented by 1


1111111111111111111111
1111111111111111111111
1111111111111111111111
1111111111111111111111
1111111111111111111111
1111111111111111111111

1111111111111111111111

and then I would like to make several pixels transparent represented by 0


1111111111111111111111
1111100000000000011111
1111111100000011111111
1111111111001111111111
1111111100000011111111
1111100000000000011111
1111111111111111111111


Would that be possible using blend modes?


P.S. I'm using version 0.8.0. of Love2D



Answer



You want a stencil.


Stencils let you flexibly define regions that love.graphics operations won't affect.


Here's an example. It does this:



  1. Draw some colourful circles.

  2. Set an inverted stencil made of two triangles.


  3. Draw a black rectangle over everything.


the result


See how the black rectangle doesn't actually cover everything? It's cut out where the triangles were. That's the stencil.


Here's the code I for that:


love.graphics.setBackgroundColor(255,255,255)

function love.draw()
local rect = love.graphics.rectangle
local circ = love.graphics.circle

local col = love.graphics.setColor
local poly = love.graphics.polygon

-- reset stencil
love.graphics.setStencil(nil);
-- draw some colorful circles
col(255,0,0)
circ("fill", 75,30, 20)
col(0,0,255)
circ("fill", 10,30, 30)

col(255,0,255)
circ("fill", 70,70, 20)
col(255,255,0)
circ("fill", 30,60, 30)

-- set stencil to an hourglass shape
love.graphics.setInvertedStencil(function()
poly("fill", 10,10, 50,50, 90,10)
poly("fill", 10,90, 50,50, 90,90)
end)

-- draw a black rectangle
col(0,0,0)
rect("fill", 0,0,100,100)
end

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...