Without shadows
The most direct approach is to have a PNG image with the texture of a light. If you don't want to use an external file, you can even create it yourself inside the program:
- Create a new white
sf::Image
of dimensions radius*radius.
- Iterate through all its pixels, setting their alpha value as 1 minus the normalized distance to the center of the image.
I recommend you drawing it with additive blend mode sf::BlendAdd
. Also, check this substractAlpha
mode; you can use this if you have a sf::RenderTexture
acting as a layer of darkness. Draw the light in that layer using this blend mode to see through.
sf::BlendMode substractAlpha(
sf::BlendMode::Factor::Zero, // color src
sf::BlendMode::Factor::One, // color dst
sf::BlendMode::Equation::Add, // color eq
sf::BlendMode::Factor::Zero, // alpha src
sf::BlendMode::Factor::OneMinusSrcAlpha, // alpha dst
sf::BlendMode::Equation::Add); // alpha eq
With shadows
Although you don't need shadows, I'll leave this here for other people that visit this question.
Dynamic 2D light is a more complex topic, as it involves raycasting algorithms and such. So instead of explaining anything here, I'll point you to a great tutorial (in fact I would recommend anyone to watch all the videos in this channel, they're all fantastic).
Line Of Sight or Shadow Casting in 2D by javidx9.
Although he doesn't use SFML, it is pretty framework-agnostic and everything he does in the OLC engine you can do it with sf::VertexArray
.
Alternative: use an existing library
There already exist open source libraries for lighting and dynamic light casting in SFML.
Let there be light (LTBL2)
GitHub repository
SFML forum thread
- Pros
- Relies on GLSL shaders, so it's probably more efficient.
- Provides soft shadows (with penumbras/antumbras).
- Cons
- It has very little documentation.
- Although the project had some updates in 2020, the development stopped in 2016 and doesn't seem to be currently active.
Candle
GitHub repository
SFL forum thread
Documentation
- Pros
- It is currently actively developed and maintained.
- It is extensively documented and comes with an out-of-the-box demo to test it (without external dependencies).
- Cons
- As a more recent library, it is not exhaustively tested and might still have glitches.
- Depending on your needs, it might not be the best performant option.