2D topdown Water Ripple Effect(片段着色器)

时间:2015-09-30 15:17:18

标签: opengl-es cocos2d-iphone cocos2d-x

所以这里是我发现的代码: 的 RippleSprite.cpp

void RippleEffectSprite::update(float delta) { //called per frame
updateRippleParams();
// TODO: improve
float rippleSpeed = 0.25f;
float maxRippleDistance = 1;
m_rippleDistance += rippleSpeed * delta;
m_rippleRange = (1 - m_rippleDistance / maxRippleDistance) * 0.02f;

if (m_rippleDistance > maxRippleDistance) {
    updateRippleParams();
    unscheduleUpdate(); //stop updating
    }
}

void RippleEffectSprite::updateRippleParams() {
getGLProgramState()->setUniformFloat("u_rippleDistance", m_rippleDistance);
getGLProgramState()->setUniformFloat("u_rippleRange", m_rippleRange);
}

片段着色器

varying vec4 v_fragmentColor; 
varying vec2 v_texCoord;

uniform float u_rippleDistance;
uniform float u_rippleRange;

float waveHeight(vec2 p) {
    float ampFactor = 2;
    float distFactor = 2;
    float dist = length(p);
    float delta = abs(u_rippleDistance - dist);
    if (delta <= u_rippleRange) {
        return cos((u_rippleDistance - dist) * distFactor) * (u_rippleRange - delta) * ampFactor;
    }
    else {
        return 0;
    }
}

void main() {
    vec2 p = v_texCoord - vec2(0.5, 0.5);
    vec2 normal = normalize(p);
    // offset texcoord along dist direction
    vec2 v_texCoord2 = v_texCoord + normal * waveHeight(p);

    gl_FragColor = texture2D(CC_Texture0, v_texCoord2) * v_fragmentColor;
}

现在我会尽力用英语来描述它,当它运行时,它会在Sprite的中间创建一个小圆圈(不是真正的圆形,更像椭圆形),然后它会慢慢向外扩展,纹理下面会像波浪一样扭曲一下。 我已经阅读了有关Shaders的内容一周了,我了解它们是如何工作的,但是我不了解这个算法,任何人都可以向我解释它是如何创建一个椭圆形并使其均匀的#39;,慢慢扩大?

这里是教程的链接:http://www.cocos.com/doc/tutorial/show?id=2121

0 个答案:

没有答案