现在来实现敌机类
敌机和我方飞机相似,具有生命值、能够发射子弹,并且有自己的运动轨迹。其实可以为它们设计一个共同的基类,这样可以更方便扩展。
不同的敌机,应设置不同的标识、属性
// 敌机生命值 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; }根据敌机类型,绑定相应的图片和生命值,对于我方飞机,如果想根据生命值来设定不同的飞机样式,也可以通过此类方法。 原文链接:https://www.f2er.com/cocos2dx/341661.html