这个计算到底是什么意思?

时间:2019-04-07 14:12:17

标签: math glsl webgl shader

我是GLSL的新手,正在这里学习本教程。 (它正在使用ShaderToy)

https://gamedevelopment.tutsplus.com/tutorials/a-beginners-guide-to-coding-graphics-shaders--cms-23313

我的问题是为什么可以通过将fragCoord的x坐标除以iResolution(screensize)来将x坐标设置为0-1。

这可能只是一个数学问题,但是我很困惑“ iResolution.x”的确切含义或在这里进行哪种计算。 (这是矢量除法吗?)

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    vec2 xy = fragCoord.xy; //We obtain our coordinates for the current pixel
    xy.x = xy.x / iResolution.x; //We divide the coordinates by the screen size
    xy.y = xy.y / iResolution.y;
    // Now x is 0 for the leftmost pixel, and 1 for the rightmost pixel
    vec4 solidRed = vec4(0,0.0,0.0,1.0); //This is actually black right now
    if(xy.x > 0.5){
        solidRed.r = 1.0; //Set its red component to 1.0
    }
    fragColor = solidRed;
}

2 个答案:

答案 0 :(得分:2)

iResolution.x是屏幕的宽度,以像素为单位。将像素x位置除以总宽度会将位置转换为屏幕宽度的一部分。因此,如果您的屏幕为1000像素宽,并且当前位置为x = 500,则xy.x = xy.x / iResolution.x;会将xy.x转换为0.500。

答案 1 :(得分:2)

其他答案是正确的。 public class Example : MonoBehaviour { public BoxCollider2D box01; public BoxCollider2D box02; private void OnTriggerEnter2D(Collider2D collision) { if(collision.IsTouching(box01)) { Debug.Log("1"); } else if(collision.IsTouching(box02)) { Debug.Log("2"); } } } 是当前绘制的像素,fragCoord是屏幕的大小,因此

iResolution

在屏幕上给出xy.x从0到1跨度和xy.y从0到1跨度的归一化值,这似乎与注释完全一样

请务必注意,xy.x = xy.x / iResolution.x; //We divide the coordinates by the screen size xy.y = xy.y / iResolution.y iResolution是用户变量。在这种情况下,我猜您是从Shadertoy获得此GLSL的。这些变量不是WebGL或GLSL的一部分,它们由Shadertoy定义,因此其值和含义由shadertoy定义。

请注意,如果您是GLSL和WebGL的新手,则可能需要考虑使用webgl tutorials。另请参见this answer about shadertoy