Why it is so hard to draw a red rectangle Sprite on white background Layer with cocos2d-x?


#1

I want to do the simplest thing in the world via cocos2d-x and and I have problems. I need a white layer on that a red rectangle. First I have found out the in order to color a layer I have to derive from cocos2d::LayerColor and LayerColor::initWithColor(Color4B(255, 255, 255, 255)) then I learnt that in order to draw a rectangle I should override draw method like this:

void HelloWorld::draw()
{
    DrawPrimitives::setDrawColor4F(1.0f, 0.0f, 0.0f, 1.0f);
    DrawPrimitives::drawRect(Point(100,100), Point(400,400));
}

This things work separatlely, but they don’t work together. I guess when I override draw, then all drawing reduces to these two function calls, hence the background of my layer becomes black. Where is the solution of this simplest thing?

EDIT:

I have tried to call LayerColor::draw in the overridden one like this:

void HelloWorld::draw()
{
    LayerColor::draw();
    DrawPrimitives::setDrawColor4F(1.0f, 0.0f, 0.0f, 1.0f);
    DrawPrimitives::drawRect(Point(100,100), Point(400,400));
}

Didn’t help. Tried to derive from sprite and addChild to the layer like this:

class BoardView : public Sprite 
{
public:
    BoardView() : Sprite() 
    {
    }

    virtual void draw() override 
    {
       DrawPrimitives::setDrawColor4F(1.0f, 0.0f, 0.0f, 1.0f);
        DrawPrimitives::drawRect(Point(100,100), Point(400,400));
    }
};

But this didn’t work either! How can I do this simplest thing? Did I miss something?


#2

Hey what helped me to learn about the subject is to look at this file :

\cocos2d-x-3.0beta2\cocos2d-x-3.0beta2\samples\Cpp\TestCpp\Classes\DrawPrimitivesTest\DrawPrimitivesTest.cppDrawPrimitivesTest.cpp

its in the example tree look for this i think you are missing :

void DrawPrimitivesTest::draw()
{
    _customCommand.init(_globalZOrder);
    _customCommand.func = CC_CALLBACK_0(DrawPrimitivesTest::onDraw, this);
    Director::getInstance()->getRenderer()->addCommand(&_customCommand);
}

this is the new way to call the renderer


#3

Try CCDrawNode plz, add it as a childto a CCLayerColor parant, you can get what you want


#4

Thanks for responses guys! :slight_smile:

I am coming with AS3 (Flesh) experience. And there you can draw graphics inside the sprite like this:

   var square:Sprite = new Sprite();
   addChild(square);
   square.graphics.lineStyle(3,0x00ff00);
   square.graphics.beginFill(0x0000FF);
   square.graphics.drawRect(0,0,100,100);
   square.graphics.endFill();

But I don’t understand where you draw when you call DrawPrimitives::drawRect.

@niuroujiang why I have to addChild to the parent of CCLayerColor, which is the scene in my case?

@Meir_yanovich I will take a look for the examples, but again please, if you can, explain me where I draw when I call DrawPrimitives::drawRect.


#5

wo ye yu dao le zhe ge wen ti
louzhu zen me jie jue de a ?
ni xie de shi js
c++ zen me gao