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


發佈了41 篇原創文章 · 獲贊 16 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章