【问题标题】:Cocos2d-x: How can I draw a resizing rectangle?Cocos2d-x:如何绘制调整大小的矩形?
【发布时间】:2015-03-15 16:12:16
【问题描述】:

我正在使用 Cocos2d-x 3.4 开发一个项目(BTW 很棒的框架 :))。我想知道如何绘制一个简单的半透明选择,与您在 Windows 上看到的选择相同?

http://cdn.maximumpcguides.com/windows-7/wp-content/uploads/2010/11/use-translucent-select-rectangle-2.png

我尝试使用 DrawNode 类,但未能实现这一点:'(我希望有人能告诉我正确的方法,请:-)

【问题讨论】:

    标签: c++ cocos2d-x-3.0


    【解决方案1】:

    使用 DrawNode 绘制非常容易。

    在 onTouchBegan 事件上设置起点,在 onTouchMoved 事件上设置终点。

    // HelloWorld.h
    class HelloWorld : public Layer{
    public:
        ...
        bool onTouchBegan(const Touch *touch, Event *event);
        void onTouchMoved(const Touch *touch, Event *event);
        void onTouchEnded(const Touch *touch, Event *event);
    
    protected:
        Vec2 _originPoint;
        Vec2 _destinationPoint;
        DrawNode *_drawNode;
    };
    
    
    // HelloWorld.cpp 
    bool HelloWorld::init()
    {
        if ( !Layer::init() ) return false;
    
        // Add touch listener
        auto listener = EventListenerTouchOneByOne::create();
        listener->setSwallowTouches(true);
        listener->onTouchBegan = CC_CALLBACK_2(HelloWorld::onTouchBegan, this);
        listener->onTouchMoved = CC_CALLBACK_2(HelloWorld::onTouchMoved, this);
        listener->onTouchEnded = CC_CALLBACK_2(HelloWorld::onTouchEnded, this);
        _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
    
        // Create the draw node
        _drawNode = DrawNode::create();
        addChild(_drawNode);
    
        return true;
    }
    
    bool HelloWorld::onTouchBegan(const cocos2d::Touch *touch, cocos2d::Event *event)
    {
        _originPoint = touch->getLocation();
        _destinationPoint = _originPoint;
    
        return true;
    }
    
    void HelloWorld::onTouchMoved(const cocos2d::Touch *touch, cocos2d::Event *event)
    {
        _destinationPoint = touch->getLocation();
    
        _drawNode->clear();
        _drawNode->drawSolidRect(_originPoint, _destinationPoint, Color4F(0,0,1,0.2));
        _drawNode->drawRect(_originPoint, _destinationPoint, Color4F::BLUE);
    }
    
    void HelloWorld::onTouchEnded(const cocos2d::Touch *touch, cocos2d::Event *event)
    {
        _drawNode->clear();
    }
    

    【讨论】:

    • 好吧……我使用了相同的代码,但它没有用,但我明白了原因,这完全是愚蠢的。我忘记在 onTouchMoved(Touch*, Event*) 方法上更新 _destinationPoint = touch->getLocation();。真丢脸:-/非常感谢!
    最近更新 更多