首页 > 代码库 > Cocos2d-x3.1 多点触摸

Cocos2d-x3.1 多点触摸

#include "cocos2d.h"
#include "ui/CocosGUI.h"
USING_NS_CC;
using namespace ui;

class HelloWorld : public cocos2d::Layer
{
public:
    // there's no 'id' in cpp, so we recommend returning the class instance pointer
    static cocos2d::Scene* createScene();

    // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
    virtual bool init();  
    
    void onTouchesBegan(const std::vector<Touch*>& touches,cocos2d::Event* event);
    void onTouchesMoved(const std::vector<Touch*>& touches,cocos2d::Event* event);
    void onTouchesEnded(const std::vector<Touch*>& touches,cocos2d::Event* event);
    void onTouchesCancel(const std::vector<Touch*>& touches,cocos2d::Event* event);
    // a selector callback
    void menuCloseCallback(cocos2d::Ref* pSender);
    
    // implement the "static create()" method manually
    CREATE_FUNC(HelloWorld);
};


#include "HelloWorldScene.h"
#include "ui/CocosGUI.h"
USING_NS_CC;
using namespace ui;
static const Color3B* s_TouchColors[EventTouch::MAX_TOUCHES] = {
    &Color3B::YELLOW,
    &Color3B::BLUE,
    &Color3B::GREEN,
    &Color3B::RED,
    &Color3B::MAGENTA
};

class TouchPoint : public Node
{
public:
    //默认构造函数
    TouchPoint()
    {
        setGLProgramState(GLProgramState::getOrCreateWithGLProgramName(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR));
    }
    //draw函数
    virtual void draw(Renderer *renderer,const Mat4 & transform, bool transformUpdated)
    {
        //设置线条颜色
        DrawPrimitives::setDrawColor4B(_touchColor.r, _touchColor.g, _touchColor.b, 255);
        //设置线条宽度
        glLineWidth(10);
        //画X、Y方向两条直线
        DrawPrimitives::drawLine(Vec2(0,_touchPoint.y),Vec2(getContentSize().width,_touchPoint.y));
        DrawPrimitives::drawLine(Vec2(_touchPoint.x,0),Vec2(_touchPoint.x,getContentSize().height));
        //设置线条宽度
        glLineWidth(1);
        //设置点大小
        DrawPrimitives::setPointSize(30);
        //画点
        DrawPrimitives::drawPoint(_touchPoint);
    }
    //设置触摸点位置
    void setTouchPos(const Vec2& pt)
    {
        _touchPoint = pt;
    }
    //设置触摸点颜色
    void setTouchColor(Color3B color)
    {
        _touchColor = color;
    }
    //构造触摸点
    static TouchPoint* touchPointWithParent(Node* pParent)
    {
        auto pRet = new TouchPoint();
        pRet->setContentSize(pParent->getContentSize());
        pRet->setAnchorPoint(Vec2::ZERO);
        pRet->autorelease();
        return pRet;
    }
    
private:
    Vec2 _touchPoint;
    Color3B _touchColor;
};


Scene* HelloWorld::createScene()
{
    // 'scene' is an autorelease object
    auto scene = Scene::create();
    
    // 'layer' is an autorelease object
    auto layer = HelloWorld::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }
    
    Size visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();

    /////////////////////////////
    // 2. add a menu item with "X" image, which is clicked to quit the program
    //    you may modify it.

    // add a "close" icon to exit the progress. it's an autorelease object
    auto closeItem = MenuItemImage::create(
                                           "CloseNormal.png",
                                           "CloseSelected.png",
                                           CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));
    
	closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 ,
                                origin.y + closeItem->getContentSize().height/2));

    // create menu, it's an autorelease object
    auto menu = Menu::create(closeItem, NULL);
    menu->setPosition(Vec2::ZERO);
    this->addChild(menu, 1);

    //设置事件监听
    auto listener = EventListenerTouchAllAtOnce::create();
    listener->onTouchesBegan = CC_CALLBACK_2(HelloWorld::onTouchesBegan,this);
    listener->onTouchesMoved = CC_CALLBACK_2(HelloWorld::onTouchesMoved,this);
    listener->onTouchesEnded = CC_CALLBACK_2(HelloWorld::onTouchesEnded,this);
    //添加到事件分发器
    Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);
    
    //标签
    auto title = Label::createWithSystemFont("Please touch the screen", "", 24);
    title->setPosition(Vec2(200,200));
    addChild(title);
    return true;
}

static Map<int, TouchPoint*> s_map;

void HelloWorld::onTouchesBegan(const std::vector<Touch *> &touches, cocos2d::Event *event)
{
    for(auto &item : touches)
    {
        auto touch = item;
        auto touchPoint = TouchPoint::touchPointWithParent(this);//初始化触摸点
        auto location = touch->getLocation();
        
        touchPoint->setTouchPos(location);//设置触摸位置
        touchPoint->setTouchColor(*s_TouchColors[touch->getID()]);//设置颜色
        addChild(touchPoint);
        s_map.insert(touch->getID(), touchPoint);
    }
}

void HelloWorld::onTouchesMoved(const std::vector<Touch *> &touches, cocos2d::Event *event)
{
    for(auto &item : touches)
    {
        auto touch = item;
        auto pTP = s_map.at(touch->getID());
        auto location = touch->getLocation();
        pTP->setTouchPos(location);
    }
}

void HelloWorld::onTouchesEnded(const std::vector<Touch *> &touches, cocos2d::Event *event)
{
    for(auto &item : touches)
    {
        auto touch = item;
        auto pTP = s_map.at(touch->getID());
        removeChild(pTP,true);
        s_map.erase(touch->getID());
    }
}

void HelloWorld::onTouchesCancel(const std::vector<Touch *> &touches, cocos2d::Event *event)
{
    onTouchesEnded(touches, event);
}
void HelloWorld::menuCloseCallback(Ref* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
	MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
    return;
#endif

    Director::getInstance()->end();

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
}


Cocos2d-x3.1 多点触摸