如今来实现敌机类

敌机和我方飞机相似,具有生命值、能够发射子弹。而且有自己的运动轨迹。事实上能够为它们设计一个共同的基类,这样能够更方便扩展。

不同的敌机,应设置不同的标识、属性

// 敌机生命值
const int ENEMY1_MAXLIFE = 1;
const int ENEMY2_MAXLIFE = 2;
const int ENEMY3_MAXLIFE = 5;
const int ENEMY4_MAXLIFE = 10; // 敌机分数
const int ENEMY1_SCORE = 1;
const int ENEMY2_SCORE = 6;
const int ENEMY3_SCORE = 20;
const int ENEMY4_SCORE = 50;

// 敌机类型
enum EnemyType
{
Enemy1 = 1,
Enemy2,
Enemy3,
Enemy4,
};

头文件里的主要函数

void setEnemyByType(EnemyType enType);
Sprite* getSprite(); int getLife();
void loseLife();
Rect getBoundingBox();

函数的实现

void Enemy::setEnemyByType(EnemyType enType)
{
switch (enType)
{
case Enemy1:
pEnemySprite = Sprite::createWithSpriteFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName("enemy1.png"));
nLife = ENEMY1_MAXLIFE;
break;
case Enemy2:
pEnemySprite = Sprite::createWithSpriteFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName("enemy2.png"));
nLife = ENEMY2_MAXLIFE;
break;
case Enemy3:
pEnemySprite = Sprite::createWithSpriteFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName("enemy3.png"));
nLife = ENEMY3_MAXLIFE;
break;
case Enemy4:
pEnemySprite = Sprite::createWithSpriteFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName("enemy4.png"));
nLife = ENEMY4_MAXLIFE;
break;
default:
return;
break;
} this->addChild(pEnemySprite);
Size winSize = Director::getInstance()->getWinSize();
Size enemySize = pEnemySprite->getContentSize();
int minX = enemySize.width / 2;
int maxX = winSize.width - enemySize.width / 2;
int rangeX = maxX - minX;
int actualX = (rand() % rangeX) + minX; // 设置敌机Node方位 Node包括Sprite
this->setPosition(Point(actualX, winSize.height - enemySize.height / 2));
} bool Enemy::init()
{
bool pRet = true;
if (!Node::init())
{
pRet = false;
} return pRet;
} Sprite* Enemy::getSprite()
{
return pEnemySprite;
} int Enemy::getLife()
{
return nLife;
} void Enemy::loseLife()
{
--nLife;
} Rect Enemy::getBoundingBox()
{
Rect rect = pEnemySprite->boundingBox();
Point pos = this->convertToWorldSpace(rect.origin);
Rect enemyRect(pos.x, pos.y, rect.size.width, rect.size.height);
return enemyRect;
}

依据敌机类型,绑定对应的图片和生命值,对于我方飞机。假设想依据生命值来设定不同的飞机样式,也能够通过此类方法。

05-11 17:02