cocos2d-x 精灵触摸事件

Cocos2d-x版本:cocos2d-2.1rc0-x-2.1.3

编译环境:vs2010(XP)


#ifndef __TOUCHABLESPRITE_h__
#define __TOUCHABLESPRITE_h__
#include "cocos2d.h"

USING_NS_CC;

class TouchableSprite: public CCSprite, public CCTargetedTouchDelegate
{

public:
	TouchableSprite();
	virtual ~TouchableSprite();

	static TouchableSprite *touchSpriteWithFile(const char *file);

	bool initWithFile(const char *file);

	virtual void onEnter();
	virtual void onExit();

	CCRect rect();

	virtual bool ccTouchBegan(CCTouch *touch, CCEvent *event);
	virtual void ccTouchMoved(CCTouch *touch, CCEvent *event);
	virtual void ccTouchEnded(CCTouch *touch, CCEvent *event);

};

#endif  //__TOUCHABLESPRITE_h__



#include "TouchableSprite.h"

TouchableSprite::TouchableSprite()
{
}

TouchableSprite::~TouchableSprite()
{
}

TouchableSprite* TouchableSprite::touchSpriteWithFile(const char *file)
{
	TouchableSprite *sprite = new TouchableSprite();

	if (sprite && sprite->initWithFile(file)) 
	{
		sprite->autorelease();
		return sprite;
	}

	return NULL;
}

bool TouchableSprite::initWithFile(const char *file)
{
	CCSprite::initWithFile(file);

	return true;
}

void TouchableSprite::onEnter()
{
	CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, true);
	
	CCSprite::onEnter();
}

void TouchableSprite::onExit()
{
	CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
	CCSprite::onExit();
}

CCRect TouchableSprite::rect()
{
	CCSize size = getTexture()->getContentSize();
	// 瞄点在(0.5,0.5)的情况下
	return CCRectMake(-size.width / 2, -size.height / 2, size.width, size.height);

}

bool TouchableSprite::ccTouchBegan(cocos2d::CCTouch *touch, cocos2d::CCEvent *event)
{
	bool bRet = false;

	if (rect().containsPoint(convertTouchToNodeSpaceAR(touch)))
	{
		CCLog("Began");
		bRet = true;
	}

	return bRet;
}

void TouchableSprite::ccTouchMoved(cocos2d::CCTouch *touch, cocos2d::CCEvent *event)
{
	CCLog("Moved");
}

void TouchableSprite::ccTouchEnded(cocos2d::CCTouch *touch, cocos2d::CCEvent *event)
{
	CCLog("Ended");
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值