cocos2dx 3.x(绘制线条)

//

//  MainScene.hpp

//  helloworld

//

//  Created by apple on 16/9/19.

//

//

 

#ifndef MainScene_hpp

#define MainScene_hpp

 

#include <stdio.h>

#include "cocos2d.h"

 

using namespace cocos2d;

//定义一个场景类

 

class MainScene : public cocos2d::Layer{

private:

    // 成员变量(私有的)

    cocos2d::Sprite *sprite;//定义一个精灵成员变量

    Size size;

public:

    virtual bool init(); // 虚函数,返回值为布尔类型,没有函数

    

    static cocos2d::Scene* createScene();//static是一个类方法返回场景

    

    void menuCallback(Ref* pSender);

    

    CREATE_FUNC(MainScene);

    

    //重载draw方法

    virtual void draw(Renderer *renderer, const Mat4 &transform, uint32_t flags) override;

    

protected:

    //自定义draw实现

    void onDraw(const cocos2d::Mat4 &transform, bool transformUpdated);

    cocos2d::CustomCommand _customCommand;

    

};

 

 

#endif /* MainScene_hpp */

 

 

 

 

 

 

 

//

//  MainScene.cpp

//  helloworld

//

//  Created by apple on 16/9/19.

//

//

 

#include "MainScene.hpp"

USING_NS_CC;

Scene * MainScene::createScene()

{

     auto scene = Scene::create();

//    CCScene * scene = CCScene::create();// 创建场景

    //创建层

    MainScene *layer = MainScene::create();

    scene->addChild(layer);

    return scene;

}

bool MainScene::init(){

    if (!Layer::init()) {

        return false;

    }

    

    //获取屏幕大小

    size = Director::getInstance()->getVisibleSize();

    //auto size = Director::getInstance()->getWinSize();

    

    return true;

}

 

 

void MainScene::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)

{

    _customCommand.init(_globalZOrder);

    _customCommand.func = CC_CALLBACK_0(MainScene::onDraw, this, transform, flags);

    renderer->addCommand(&_customCommand);

}

 

void MainScene::onDraw(const cocos2d::Mat4 &transform, bool transformUpdated)

{

    //利用Stack缓存

    Director *director = Director::getInstance();

    //CCASSERT(nullptr != director, "Director is null when setting matrix stack");

    director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);

    director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, transform);

    

    CHECK_GL_ERROR_DEBUG();

    

    //画边框

    DrawPrimitives::setDrawColor4B(255, 255, 255, 255);

    glLineWidth(10);

    Vec2 vertices[] = {Vec2(100, 100), Vec2(300, 100), Vec2(300, 300), Vec2(100, 300)};

    DrawPrimitives::drawPoly(vertices, 4, true);

    

    CHECK_GL_ERROR_DEBUG();

    

    //绘制停止,释放

    director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);

}

 

void MainScene::menuCallback(Ref* pSender)

{

    

}

 

原文地址:https://www.cnblogs.com/luorende/p/6658575.html