.众所周知,Box2d的DrawDebugData函数绘制默认不是放在最前面的,为了达到这个要求,v2版代码很简单
v2:
void Box2dManager::draw(){ ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position );
kmGLPushMatrix();
Box2dWorld->DrawDebugData();
kmGLPopMatrix();
}
v3:
v3版找了很久,貌似研究的人不多,不过找的过程中,有人分析v3为了提高性能,将v2那种单独渲染变成了集中渲染,在draw中并不马上执行渲染,这时候使用代码:
void Box2dManager::draw(Renderer *renderer,const Mat4& transform,uint32_t flags){
GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POSITION );
Director::getInstance()->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
Box2dWorld->DrawDebugData();
Director::getInstance()->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
}
这个写法是完全从v2过度过来的,但很遗憾,并没有实现该有的功能
而根据v3方式把要渲染的顺序加入到渲染序列中,通过调用onDraw来进行上面的代码,这时候才能有效的让渲染悬浮在其他sprite之上
void Box2dManager::draw(Renderer *renderer,uint32_t flags){
super::draw(renderer,transform,_transformUpdated);
GL::enableVertexAttribs( cocos2d::GL::VERTEX_ATTRIB_FLAG_POSITION );
Director* director = Director::getInstance();
CCASSERT(nullptr != director,"Director is null when seting matrix stack");
director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
_modelViewMV = director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
_customCommand.init(_globalZOrder);
_customCommand.func = CC_CALLBACK_0(Box2dManager::onDraw,this);
renderer->addCommand(&_customCommand);
director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
}
void Box2dManager::onDraw() {
Director* director = Director::getInstance();
CCASSERT(nullptr != director,"Director is null when seting matrix stack");
Mat4 oldMV;
oldMV = director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW,_modelViewMV);
Box2dWorld->DrawDebugData();
director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW,oldMV);
}
参考:
Box2d debug drawing for cocos2d-x 3.0
B2DebugDrawLayer attachment
Cocos2d-x 3.2的渲染流程