2
\$\begingroup\$

I'm a beginner trying to implement a flashlight in SDL2, but can't figure out a good way to do it.

I've found a way to manipulate the background's color; changed it to dark and back to its normal colors, but this isn't the whole solution.

My main goal is a flashlight that follows the player around the map.

I thought about per-pixel drawing, but I think it will result in poor performance. Drawing a black pixel for every pixel on screen, then changing back the to the normal color to all of the pixels surrounding the player.

How do I do this correctly?(BTW, I'm using a 'SDL_Renderer', not 'SDL_Surface', i realized this can be a problem when dealing with pixels.)

\$\endgroup\$
1
  • \$\begingroup\$ Are we talking about 2D sprites or a 3D flashlight like in Doom 3? For the latter, search for projective spotlight texture. \$\endgroup\$
    – glampert
    Commented Dec 10, 2015 at 17:14

2 Answers 2

1
\$\begingroup\$

For a very simple effect just load an alpha image with a white circle in the center and otherwise all black into an SDL_Texture and render it centered to your character. Anything inside the white circle will stay visible while the rest will become black.

You could also make the texture animated creating a "candlelight" effect. You could also scale the texture for stronger/weaker lighting. You can create a smooth transition with making the alpha in the image be a radial gradient. You don't even have to make it an image file, it could be generated on init into a SDL_Surface then converted to an SDL_Texture. just make sure you use the alpha value correctly.

\$\endgroup\$
0
\$\begingroup\$

You can use per-pixel drawing in precalc stage of your engine, and then use glTexImage2d to move the data to GPU, and then rest of the rendering primitives can be done quickly in every frame.

So for flashlight, you'd just draw a filled circle first, then negate the bitmap.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .