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");
}