cocos2dx shader实现深入浅出的背景

前端之家收集整理的这篇文章主要介绍了cocos2dx shader实现深入浅出的背景前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

<1>

void update(float dt);
void updateLocation(GLProgram* program,Uniform* uniform);
Sprite* _ballSp;
Vec2 _ballPosition;
<2>
//
Size winSize = Director::getInstance()->getWinSize();

//
auto program = GLProgram::createWithFilenames("light.vert","light.frag");
auto pstate = GLProgramState::create(program);
pstate->setUniformCallback("ballPosition",CC_CALLBACK_2(HelloWorld::updateLocation,this));

//
Sprite* water = Sprite::create("HelloWorld.png");
water->setPosition(Vec2(winSize.width / 2,winSize.height / 2));
water->setScale(winSize.width / water->getContentSize().width);
water->setGLProgramState(pstate);
this->addChild(water);

// 	
_ballSp = Sprite::create();
_ballSp->setPosition(Vec2(winSize.width / 2,water->getContentSize().height * (winSize.width / water->getContentSize().width) / 2 + winSize.height / 2));
this->addChild(_ballSp);

//
MoveTo* moveTo = MoveTo::create(10,Vec2(winSize.width / 2,winSize.height / 2 - water->getContentSize().height*(winSize.width / water->getContentSize().width) / 2));
_ballSp->runAction(moveTo);

//
this->scheduleUpdate();
<3>
void HelloWorld::update(float dt){
	_ballPosition = _ballSp->getPosition();
}

void HelloWorld::updateLocation(GLProgram* program,Uniform* uniform){
	program->setUniformLocationWith2f(uniform->location,_ballPosition.x,_ballPosition.y);
}
<4>light.vert
attribute vec4 a_position;
attribute vec2 a_texCoord;
attribute vec4 a_color;
uniform   vec2 ballPosition;

#ifdef GL_ES
    varying lowp vec4 v_fragmentColor;
    varying mediump vec2 v_texCoord;
    varying lowp float v_alpha;
#else
    varying vec4 v_fragmentColor;
    varying vec2 v_texCoord;
    varying float v_alpha;
#endif

void main()
{
    float distance;
    gl_Position = CC_MVPMatrix * a_position;
    v_fragmentColor = a_color;
    v_texCoord = a_texCoord;
    v_alpha = 0.0;
    if(ballPosition.y < a_position.y){
        distance = a_position.y - ballPosition.y
	v_alpha = distance * 2.0 / a_position.y;
    }else{
        distance = ballPosition.y - a_position.y;
	v_alpha = (a_position.y - distance) / a_position.y;
    }
}
<5>light.frag
#ifdef GL_ES
    precision lowp float;
#endif

varying vec4 v_fragmentColor;
varying vec2 v_texCoord;
varying float v_alpha;

void main()
{
    gl_FragColor = v_alpha * v_fragmentColor * texture2D(CC_Texture0,v_texCoord);
}
原文链接:https://www.f2er.com/cocos2dx/343005.html

猜你在找的Cocos2d-x相关文章