cocos2dx C++為Sprite添加觸摸事件監聽器


1.首先頭文件定義事件處理的函數原型

private:
	bool onTouchBegan(Touch* tTouch,Event* eEvent);//手指按下事件
	void onTouchMoved(Touch* tTouch,Event* eEvent);//手指移動事件
	void onTouchEnded(Touch* tTouch,Event* eEvent);//手指離開事件

2.實現原型

bool ShopItem::onTouchBegan(Touch* tTouch,Event* eEvent){
 if (sprite->getBoundingBox().containsPoint(tTouch->getLocation())){//判斷觸摸點是否在目標的范圍內

    /**這里為事件內容**/
    return true;
 }else
    return false;
 }	
}

void ShopItem::onTouchMoved(Touch* tTouch,Event* eEvent){
	/**這里為事件內容**/
}

void ShopItem::onTouchEnded(Touch* tTouch,Event* eEvent){
	/**這里為事件內容**/
}

3.綁定事件

auto listener = EventListenerTouchOneByOne::create();
	listener->onTouchBegan = CC_CALLBACK_2(ShopItem::onTouchBegan, this);
	listener->onTouchMoved = CC_CALLBACK_2(ShopItem::onTouchMoved, this);
	listener->onTouchEnded = CC_CALLBACK_2(ShopItem::onTouchEnded, this);
	this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, sprite);

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM