在Cocos2d-X3.0中实现多点触摸

在上一篇博客介绍了在Cocos2d-X3.0中实现单点触摸,但是有些游戏还会用到多点触摸,其中最典型的的游戏室节奏大师,在节奏大师中会不断产生运动的音符,玩家需要不停的点击音符以获得高分,而且玩家可以多个手指头一起点,多个手指头一起点就是使用多点触摸实现的

下面通过一个小的例子介绍如何在Cocos2d-X3.0中实现多点触摸

首先创建一个touches类,并且在touches.h中添加下面的代码

#ifndef _touches_H_
#define _touches_H_

#include "cocos2d.h"
USING_NS_CC;

class touches : public Layer
{
public:
	touches(void);
	~touches(void);

	CREATE_FUNC(touches);
	static Scene* createScene();
	bool init();

	//开始触摸
	void ontouchesBegan(const std::vector<Touch*>& touches,Event  *event);
    
	//滑动
	void ontouchesMoved(const std::vector<Touch*>& touches,Event  *event);
    
	//结束触摸
	void ontouchesEnded(const std::vector<Touch*>& touches,Event  *event);

	//取消触摸
	void ontouchesCancelled(const std::vector<Touch*>& touches,Event  *event);
};

#endif
 

touches.cpp中添加下面的代码

#include "touches.h"


touches::touches(void)
{
}


touches::~touches(void)
{
}


Scene* touches::createScene()
{
	auto scene = Scene::create();

	auto layer = touches::create();

	scene->addChild(layer);

	return scene;
}


bool touches::init()
{
	if(!Layer::init())
	{
		return false;
	}

	//创建一个事件监听器,AllAtOne为多点触摸
    auto listener = EventListenerTouchAllAtOnce::create();

	//事件回调函数
	listener->ontouchesBegan = CC_CALLBACK_2(touches::ontouchesBegan,this);
    listener->ontouchesMoved = CC_CALLBACK_2(touches::ontouchesMoved,this);
    listener->ontouchesEnded = CC_CALLBACK_2(touches::ontouchesEnded,this);
    
	//添加监听器
	_eventdispatcher->addEventListenerWithSceneGraPHPriority(listener,this);
        

	return true;
}


//开始触摸
void touches::ontouchesBegan(const std::vector<Touch*>& touches,Event  *event)
{
	log("touches began !");
}
    

//滑动
void touches::ontouchesMoved(const std::vector<Touch*>& touches,Event  *event)
{
	log("touches moved !");
}
    

//结束触摸
void touches::ontouchesEnded(const std::vector<Touch*>& touches,Event  *event)
{
	log("touches enaded !");
}


//取消触摸
void touches::ontouchesCancelled(const std::vector<Touch*>& touches,Event  *event)
{
	ontouchesEnded(touches,event);
}

程序测试的结果:
当触摸屏幕时会打印touches began !
当触摸结束后会打印touches ended !
当在屏幕上滑动时会打印touches moved !

相关文章

    本文实践自 RayWenderlich、Ali Hafizji 的文章《...
Cocos-code-ide使用入门学习地点:杭州滨江邮箱:appdevzw@1...
第一次開始用手游引擎挺激动!!!进入正题。下载资源1:从C...
    Cocos2d-x是一款强大的基于OpenGLES的跨平台游戏开发...
1.  来源 QuickV3sample项目中的2048样例游戏,以及最近《...
   Cocos2d-x3.x已经支持使用CMake来进行构建了,这里尝试...