Question

i try to draw bounding box around the Sprite i added to layer and position it somewhere the CC_SPRITE_DEBUG_DRAW flag don't work in version 3 but i toke the code from CCSprite

i use this code in spirit draw method :

Point vertices1[4] = {
        Point( _quad.bl.vertices.x, _quad.bl.vertices.y ),
        Point( _quad.br.vertices.x, _quad.br.vertices.y ),
        Point( _quad.tr.vertices.x, _quad.tr.vertices.y ),
        Point( _quad.tl.vertices.x, _quad.tl.vertices.y ),
    };

    DrawPrimitives::setDrawColor4B(255, 255, 0, 255);
    glLineWidth(2);
     Point(50,100) };
    DrawPrimitives::drawPoly( vertices, 4, true);

but it gives me the world space position that is drawing the Sprite in the low left corner of the main window and not the spirit position. how can i fix this ?

ps i saw something here but i dont know how to translate it to cocos2d-x 3 http://www.naveoss.com/site/450/tutorials/opengl-drawing-boxes-around-ccsprite-subclasses

Was it helpful?

Solution

Please have a try at the following snippet (this is still cocos2dx v2 but you can easily upgrade it to v3).

void YourSprite::draw()  {
    ccGLEnableVertexAttribs(kCCVertexAttribFlag_Position);
    kmGLPushMatrix();
    CCRect bb = boundingBox();
    CCPoint vertices[4] = {
        CCPoint( bb.origin.x, bb.origin.y ),
        CCPoint( bb.origin.x, bb.origin.y + bb.size.height ),
        CCPoint( bb.origin.x + bb.size.width, bb.origin.y + bb.size.height ),
        CCPoint( bb.origin.x + bb.size.width, bb.origin.y)
    };
    ccDrawColor4B(255, 255, 0, 255);
    glLineWidth(2);

    ccDrawPoly(vertices, 4, true);
    kmGLPopMatrix(); }

Also check out CCDrawNode and drawPolygon which has better performance than DrawPrimitive.

PS: note that you should reset the line width to its previous state.

    float oldWidth = .0f;
    glGetFloatv(GL_LINE_WIDTH, &oldWidth);
    /// Set new line width
    glLineWidth(mLineWidth);
  ....
    /// Reset previous line width
    glLineWidth(oldWidth);

OTHER TIPS

Starting with Cocos2d-x 3.3 you can use DrawNode class to draw shapes. It inherits from Node so you can add it as a child or use it as a parent.

auto box = DrawNode::create();
box::drawRect(p1, p2, p3, Color4F(255, 255, 0, 255));
box::setLineWidth(2)
this->addChild(box); // this being a node or scene

There is also

void drawPoint(const Vec2& point, const float pointSize, const Color4F &color);
void drawLine(const Vec2 &origin, const Vec2 &destination, const Color4F  &color);`

and other cool stuff that reminds you of UIBezierPath from Cocoa.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top