您的位置:首页 > 移动开发 > Cocos引擎

cocos2d-x 植物大战僵尸(6) 触摸植物卡的消息响应

2013-12-05 11:15 639 查看
大家中午好,今天要说的是:触摸植物卡的消息响应;我呢,已经写好了触摸消息响应层,触摸这个过程我觉得还是写在层这个档位上比较好,为什么呢?因为CCLayer层本身他是继承CCtouchDelegate的,所以这可省去很多麻烦,我们要做的工作是在TouchLayer层中重载CCTouchDelegate中的方法即可!这次的博客主要是说下测试触摸响应的过程;有朋友说我那个华为网盘上的资源下载不了,这不科学。回头我再看下是怎么回事;

好,开始吧:

首先我来建一个触摸层TouchLayer,它的作用是监听整个游戏一切的触摸活动;

在TouchLayer.h中:进行以下声明:

#pragma once
#include "e:\cocos2d-x\cocos2d-x-2.2\cocos2d-x-2.2\cocos2dx\layers_scenes_transitions_nodes\cclayer.h"
#include "cocos2d.h"
class TouchLayer :public  cocos2d::CCLayer
{
public:
	TouchLayer(void);
	~TouchLayer(void);
    virtual bool init();
	CREATE_FUNC(TouchLayer);

	void registerWithTouchDispatcher(void);//注册触摸代理
    void ccTouchesBegan(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent);;//一旦触摸开始
    void ccTouchesMoved(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent);//一旦手指按下并移动
    void ccTouchesEnded(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent);//触摸结束时

};


在TouchLayer.cpp中进行以下声明:

#include "TouchLayer.h"
#include "GameLayer.h"//利用C++多态实现消息传递
USING_NS_CC;

TouchLayer::TouchLayer(void)
{
}

TouchLayer::~TouchLayer(void)
{
}

bool TouchLayer::init()
{
	if(!CCLayer::init())
	{
		return false;
	}

	this->setTouchEnabled(true);//设置开启触摸
	return true;
}

void TouchLayer::registerWithTouchDispatcher(void)
{
	CCDirector::sharedDirector()->getTouchDispatcher()->addStandardDelegate(this,-1);//设置触摸优先级为-1
}

void TouchLayer::ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent)
{
   CCTouch* pTouch = (CCTouch*)pTouches->anyObject();//触摸多点转化为触摸单点
   if(((GameLayer*)this->getParent())->_cardLayer->_cardSprite->boundingBox().containsPoint(pTouch->getLocation()))//判断触摸是否发生在植物卡上
   {
	   MessageBox(NULL,TEXT("我可以不出来吗?"),TEXT("MSG"),MB_OK);//淡出消息框(做测试用的)
   }

}

void TouchLayer::ccTouchesMoved(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent)
{

}

void TouchLayer::ccTouchesEnded(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent)
{

}


下面,我们要完成的工作是:把我们的触摸层加到我们的主游戏层中去:

在GameLayer.h中进行以下声明:

#include "TouchLayer.h"


//声明触摸层
	TouchLayer* _touchLayer;
	void initTouchLayer();


在GameLayer.cpp的构造函数中,加上一句:

this->_touchLayer =NULL;


在void GameLayer::initTouchLayer()中进行以下定义:

void GameLayer::initTouchLayer()
{
	this->_touchLayer =TouchLayer::create();
	this->addChild(this->_touchLayer);
}


最后加到bool GameLayer::init()中去:

this->initTouchLayer();


好看下测试效果:



我再补充一点:我建议在使用触摸的两种方式上,建议大家使用标准多点触摸,至于他的好处,大家会慢慢感觉到的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: