如何在SDL2上向纹理添加阴影?

问题描述

所以,我正在制作2D游戏,并且有一些纹理。我希望他们中的一些人能投下阴影,对于SDL2,css中是否有诸如阴影之类的东西?

解决方法

首先渲染纹理,然后在其后面渲染稍大的半透明灰色正方形。如果您想要圆角,请use a shader that increases alpha as you get further from the corners

,

因为没有人提到它,所以它是:

int SDL_SetTextureColorMod(SDL_Texture* texture,Uint8        r,Uint8        g,Uint8        b)

https://wiki.libsdl.org/SDL_SetTextureColorMod

此功能在将纹理颜色通道复制到SDL_Renderer *时会使其倍增。将其与0,r,g和b参数一起使用将使您的纹理间距变黑,但不影响alpha,因此纹理将保持其形状(例如在透明PNG的情况下)。您只需要复制纹理之前(=后面)的阴影,并稍有偏移即可。您还可以使用SDL_SetTextureAlphaMod(SDL_Texture* texture,Uint8 a)

更改阴影的总体透明度

完成操作后,别忘了将值设置回255。


代码示例:

SDL_SetRenderDrawColor(renderer,255);
SDL_RenderClear(renderer);
// [...] draw background,etc... here

SDL_Rect characterRect;
// [...] fill the rect however you want
SDL_Rect shadowRect(characterRect);
shadowRect.x += 30; // offsets the shadow
shadowRect.y += 30;

SDL_SetTextureColorMod(characterTexture,0);                // makes the texture black
SDL_SetTextureAlphaMod(characterTexture,191);                    // makes the texture 3/4 of it's original opacity      
SDL_RenderCopy(renderer,characterTexture,NULL,&shadowRect);    // draws the shadow
SDL_SetTextureColorMod(characterTexture,255,255);          // sets the values back to normal
SDL_SetTextureAlphaMod(characterTexture,255);
SDL_RenderCopy(renderer,&characterRect); // draws the character

// [...] draw UI,additionnal elements,etc... here
SDL_RenderPresent(renderer);

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...