【问题标题】:How to make a take a circle out of a shader?如何从着色器中取出一个圆圈?
【发布时间】:2026-01-31 18:25:01
【问题描述】:

我正在使用 GLSL 着色器开发游戏

我将 Go 与 Pixel 库一起使用,这是一款 2d 游戏,没有“相机”(我有人建议使用第二个相机来实现这一点)

我当前的着色器只是一个基本的灰度着色器

#version 330 core
in vec2  vTexCoords;
out vec4 fragColor;
uniform vec4 uTexBounds;
uniform sampler2D uTexture;
void main() {
    // Get our current screen coordinate
    vec2 t = (vTexCoords - uTexBounds.xy) / uTexBounds.zw;
    // Sum our 3 color channels
    float sum  = texture(uTexture, t).r;
        sum += texture(uTexture, t).g;
        sum += texture(uTexture, t).b;
    // Divide by 3, and set the output to the result
    vec4 color = vec4( sum/3, sum/3, sum/3, 1.0);
    fragColor = color;
}

我想取出一圈着色器来显示对象的颜色,就像光线照在它们身上一样。

这是我正在努力实现的一个示例

我真的不知道要搜索什么来找到一个着色玩具示例或这样做的东西,但我以前见过类似的东西,所以我很确定这是可能的。

重申;我基本上只是想删除部分着色器。

不确定使用着色器是否是解决此问题的最佳方法,如果有其他方法,请告诉我,我会重新提出问题。

【问题讨论】:

    标签: glsl shader game-engine fragment-shader


    【解决方案1】:

    您可以轻松扩展它以使用任意位置作为“光”。

    1. 声明一个统一的缓冲区来存储当前位置和半径。
    2. 如果从给定位置到当前像素的距离小于半径的平方,则返回当前颜色。
    3. 否则,返回其灰度。

      vec2 displacement = t - light_location;
      float distanceSq = (displacement.x * displacement.x + displacement.y * displacement.y)
      float radiusSq = radius * radius;
      if(distanceSq < radiusSq) {
          fragColor = texture(uTexture);
      } else {
          float sum = texture(uTexture).r;
          sum += texture(uTexture).g;
          sum += texture(uTexture).b;
          float grey = sum / 3.0f;
         fragColor = vec4(grey, grey, grey, 1.0f);
      }
      

    【讨论】: