android cocos2d 触屏事件

现在的移动设备都是可触摸设备,对于触屏操作也是最理所当然或者常见的,然而我们需要通过对触屏事件进行注册,然而事件的注册,只需要我们重写几个虚函数即可做到

函数声明如下:在我们需要进行触屏事件的Scene类当中进行

    virtual    void registerWithTouchDispatcher();
    virtual  bool ccTouchBegan(CCTouch*touch,CCEvent*event);
    virtual   void ccTouchMoved(CCTouch*touch,CCEvent*event);
    virtual    void ccTouchEnded(CCTouch*touch,CCEvent*event);
    virtual   void ccTouchCancelled(CCTouch*touch,CCEvent*event);
   // virtual void onEnter();
    virtual void onExit();

    bool containsTouchLocation(cocos2d::CCTouch *touch);
    bool isControl;

我们可以这样认为

void CGameScene::registerWithTouchDispatcher() {
	//注册触摸事件
	CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(
			this, 0, true);
}

bool CGameScene::ccTouchBegan(CCTouch*touch, CCEvent*event) {
	if (containsTouchLocation(touch)) {
		isControl = true;
		//CCMessageBox("we got !!", "dsad");
		return true;
	}
	else
	{
	//	CCMessageBox("we got nothing", "dsade1");
	}
	return false;
}
void CGameScene::ccTouchMoved(CCTouch*touch, CCEvent*event) {
	if (isControl) {
		CCPoint touchPoint=convertTouchToNodeSpace(touch);
		m_hinstance->setPosition(touchPoint);
	}
}
void CGameScene::ccTouchEnded(CCTouch*touch, CCEvent*event) {
	isControl = false;
}

void CGameScene::ccTouchCancelled(CCTouch*touch, CCEvent*event) {
	isControl = false;
}
/*
void CGameScene::onEnter()
{
	CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, true);
	setTouchEnabled(true);
}*/
void CGameScene::onExit()
{
	CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
}
bool CGameScene::containsTouchLocation(cocos2d::CCTouch *touch)
{
	CCPoint touchPoint=convertTouchToNodeSpace(touch);
    return m_hinstance->boundingBox().containsPoint(touchPoint);
}
通过上述代码便能进行触摸检测,同时使得目标跟着手进行移动。

这里我要说的有一点,onEnter和registerWithTouchDispatcher两个函数,onEnter函数则是进行自动注册。而我们通过手动调用registerWithTouchDispatcher函数进行手动注册,这两个函数的函数体是一样的,只是区别在于手动和自动。

另外一点则是,进行Sprite的触摸检测

CCPoint touchPoint=convertTouchToNodeSpace(touch);
return m_hinstance->boundingBox().containsPoint(touchPoint);
这样就可以进行触摸之后的检测了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

世纪殇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值