Cocos2d-x ccSprite的触摸消息响应 - ccsx教程

关于cocos2d-x的精灵touch消息监听Demo.

//
//  TSSpirte.h
//  TSSpiriteTouch
//
//  Created by TSEnel on 13-2-23.
//
//

#ifndef __TSSpiriteTouch__TSSpirte__
#define __TSSpiriteTouch__TSSpirte__

#include <iostream>
#include "cocos2d.h"

using namespace cocos2d;

class TSSprite : public CCSprite ,public CCTouchDelegate
{
public:
    static TSSprite*  create(const char *pszFileName);

public:
    virtual void onEnter();
    virtual void onExit();
    virtual bool ccTouchBegan(CCTouch* touch, CCEvent* event);
    virtual void ccTouchMoved(CCTouch* touch, CCEvent* event);
    virtual void ccTouchEnded(CCTouch* touch, CCEvent* event);
};


#endif /* defined(__TSSpiriteTouch__TSSpirte__) */


关键点在于需要继承CCTouchDelegate. 然后完成相应的虚函数.


//
//  TSSpirte.cpp
//  TSSpiriteTouch
//
//  Created by TSEnel on 13-2-23.
//
//

#include "TSSpirte.h"

TSSprite* TSSprite::create(const char *pszFileName)
{
    TSSprite *pobSprite = new TSSprite();
    if (pobSprite && pobSprite->initWithFile(pszFileName))
    {
        pobSprite->autorelease();
        return pobSprite;
    }
    CC_SAFE_DELETE(pobSprite);
    return NULL;
}

void TSSprite::onEnter()
{
    CCDirector* pDirector = CCDirector::sharedDirector();
    pDirector->getTouchDispatcher()->addTargetedDelegate(this, 0, false);
    CCSprite::onEnter();
}

void TSSprite::onExit()
{
    CCDirector* pDirector = CCDirector::sharedDirector();
    pDirector->getTouchDispatcher()->removeDelegate(this);
    CCSprite::onExit();
}

bool TSSprite::ccTouchBegan(CCTouch* touch, CCEvent* event)
{
    CCPoint sLocalPos = convertToNodeSpace(touch->getLocation());
    CCRect sRC = CCRect(getPositionX() - getContentSize().width * getAnchorPoint().x,
                           getPositionY() - getContentSize().height * getAnchorPoint().y,
                           getContentSize().width, getContentSize().height);
    
    
    sRC.origin = CCPointZero;
    bool isTouched = sRC.containsPoint(sLocalPos);
    if(isTouched)
    {
        CCLog("点中了!! x:%d y:%d", (int)sLocalPos.x, (int)sLocalPos.y);
        return true;
    }
    else
    {
        CCLog("没点中了!! x:%d y:%d", (int)sLocalPos.x, (int)sLocalPos.y);
        return false;
    }
}

void TSSprite::ccTouchMoved(CCTouch* touch, CCEvent* event)
{
    
}

void TSSprite::ccTouchEnded(CCTouch* pTouch, CCEvent* event)
{
    
}

代码已经上传GitHub. 可以取来玩:

https://github.com/spiritring/TSSpiriteTouch.git 点击打开链接

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值