cocos2dx shader 第一个三角形<1>

前端之家收集整理的这篇文章主要介绍了cocos2dx shader 第一个三角形<1>前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

<1>HelloWorld.h

#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__

#include "cocos2d.h"
USING_NS_CC;
#include<string>
using namespace std;

class HelloWorld : public cocos2d::Layer
{
public:
    HelloWorld();
    ~HelloWorld();
    static cocos2d::Scene* createScene();
    virtual bool init();
    CREATE_FUNC(HelloWorld);
    virtual void visit(Renderer* renderer,const Mat4& parentTransform,uint32_t parentFlags);
    void onDraw();
private:
    CustomCommand _command;
};


#endif // __HELLOWORLD_SCENE_H__
<2>HelloWorld.cpp
#include "HelloWorldScene.h"
USING_NS_CC;
using namespace std;

HelloWorld::HelloWorld(){
    
}

HelloWorld::~HelloWorld(){
 
}

bool HelloWorld::init()
{
    if ( !Layer::init() ){
        return false;
    }
 
    this->setGLProgram(GLProgramCache::getInstance()->getGLProgram(GLProgram::SHADER_NAME_POSITION_COLOR));
    
    return true;
}

void HelloWorld::visit(Renderer *renderer,uint32_t parentFlags){
    Node::visit(renderer,parentTransform,parentFlags);
    _command.init(_globalZOrder);
    _command.func = CC_CALLBACK_0(HelloWorld::onDraw,this);
    Director::getInstance()->getRenderer()->addCommand(&_command);
}

void HelloWorld::onDraw(){
    auto glProgram = getGLProgram();
    glProgram->use();
    glProgram->setUniformsForBuiltins();
    auto winSize = Director::getInstance()->getWinSize();
    float vert[] = {
        0,winSize.width,winSize.width/2,winSize.height
    };
    
    float color[] = {
        0,1,//绿
        1,//红
        0,1  //蓝
    };
    
    GL::enableVertexAttribs(GL::VERTEX_ATTRIB_FLAG_POSITION | GL::VERTEX_ATTRIB_FLAG_COLOR);
    glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION,2,GL_FLOAT,GL_FALSE,vert);
    glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR,4,color);
    glDrawArrays(GL_TRIANGLES,3);
    CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(1,3);
    CHECK_GL_ERROR_DEBUG();
}

Scene* HelloWorld::createScene()
{
    auto scene = Scene::create();
    auto layer = HelloWorld::create();
    scene->addChild(layer);
    return scene;
}
原文链接:https://www.f2er.com/cocos2dx/342545.html

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