RoleSprite用来根据Role的数据类来显示不同的角色,需要有一个数据类的引用,在这里将其锚点设置在左下角,方便计算其坐标和进行碰撞检测。
属性:
m_pRole | 角色数据的引用 |
m_row | 当前所在行 |
m_col | 当前所在列 |
m_width | 横向占的格子数 |
m_height | 竖向占的格子数 |
代码:
RoleSprite.h
#ifndef _ROLE_SPRITE_H_ #define _ROLE_SPRITE_H_ #include "cocos2d.h" class Role ; class RoleSprite : public cocos2d::Node { public: static RoleSprite* create(Role * pRole,int row,int col,const cocos2d::Rect & bounds,cocos2d::Node * pParent,int zOrder); public: RoleSprite(Role * role,int col); ~RoleSprite(); virtual bool init() ; private: CC_SYNTHESIZE(Role *,m_pRole,Role); CC_SYNTHESIZE(int,m_row,Row);//<所在行 CC_SYNTHESIZE(int,m_col,Col);//<所在列 CC_SYNTHESIZE_READONLY(int,m_width,Width);//<水平方向上占的格子数 CC_SYNTHESIZE_READONLY(int,m_height,Height);//<竖直方向上占的格子数 }; #endif
RoleSprite.cpp
#include "RoleSprite.h" #include "data/Role.h" USING_NS_CC ; RoleSprite * RoleSprite::create(Role * pRole,int zOrder) { auto pRet = new RoleSprite(pRole,row,col); pRet->setContentSize(bounds.size) ; pRet->setPosition(bounds.origin) ; pRet->setAnchorPoint(Vec2(0,0)) ; if (pRet->init()) { pParent->addChild(pRet,zOrder) ; pRet->autorelease(); } else { delete pRet; return nullptr ; } return pRet ; } RoleSprite::RoleSprite(Role * role,int col) :m_pRole(nullptr),m_row(0),m_col(0),m_width(0),m_height(0) { m_pRole = role ; CC_SAFE_RETAIN(m_pRole) ; m_row = row ; m_col = col ; m_width = m_pRole->getWidth() ; m_height = m_pRole->getHeight() ; } RoleSprite::~RoleSprite() { CC_SAFE_RELEASE_NULL(m_pRole); } bool RoleSprite::init() { Sprite* pSkin = Sprite::create(m_pRole->getImageName()->getCString()) ; pSkin->setPosition(this->getBoundingBox().size.width / 2,this->getBoundingBox().size.height / 2) ; addChild(pSkin) ; return true; }