cocos2dx之如何实现自己的sprite

可能在制作游戏的过程中,用到sprite,但是它本省的方法有限,我需要再次扩充它,那么我们可以通过继承得到自定义的sprite:

定义如下:

#ifndef MYSPRITEBASE_H_
#define MYSPRITEBASE_H_

#include "cocos2d.h"
USING_NS_CC;

class MySprite : public CCSprite, public CCStandardTouchDelegate
{
public:
    MySprite();
    ~MySprite();

public:

    CCRect rect();
    bool initWithTexture(CCTexture2D* aTexture);
    void onEnter();
    void onExit();
    bool containsTouchLocation(CCTouch* touch);
    void ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent);
    void ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent);
    void ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent);

    CCObject* copyWithZone(CCZone *pZone);
    void touchDelegateRetain();
    void touchDelegateRelease();

    static MySprite *paddleWithTexture(CCTexture2D* aTexture);
    static MySprite *create(CCTexture2D *pTexture);



}; //  end of MySprite

#endif //MYSPRITEBASE_H_

在这里我们采用的消息类是用到的:CCStandardTouchDelegate类。

当然也可以用:CCTargetedTouchDelegate


具体实现:

#include "MySpriteBase.h"


MySprite::MySprite() {
    CCDirector::sharedDirector()->getTouchDispatcher()->addStandardDelegate(this, 0);
}

MySprite::~MySprite() {

}

CCRect MySprite::rect() {
    CCSize s = getTexture()->getContentSize();
    return CCRectMake(s.width / 2, -s.height / 2, s.width, s.height);
}

bool MySprite::initWithTexture(CCTexture2D* aTexture) {
    if( CCSprite::initWithTexture(aTexture) ) 
    {
        return true;
    }
    return false;
}

MySprite *MySprite::create(CCTexture2D *pTexture) {
    MySprite *pobSprite = new MySprite();
    if (pobSprite && pobSprite->initWithTexture(pTexture))
    {
        pobSprite->autorelease();
        return pobSprite;
    }
    CC_SAFE_DELETE(pobSprite);
}

void MySprite::onEnter() {

    CCSprite::onEnter();
}

void MySprite::onExit() {
    CCSprite::onExit();
}

bool MySprite::containsTouchLocation(CCTouch* touch) {
    return true;
}

void MySprite::ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent) {

}

void MySprite::ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent) {

}

void MySprite::ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent) {

}

CCObject* MySprite::copyWithZone(CCZone *pZone) {
    this->retain();
    return this;
}

void MySprite::touchDelegateRetain() {
    this->retain();
}

void MySprite::touchDelegateRelease() {
    this->release();
}

MySprite* paddleWithTexture(CCTexture2D* aTexture) {
    MySprite* pPaddle = new MySprite();
    pPaddle->initWithTexture( aTexture );
    pPaddle->autorelease();
    return pPaddle;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值