分析:
敌人也有自己的动作,也定义为Sprite类
也需要做碰撞检测,故设置物理属性
敌人不断地从屏幕右端移到左端,用MoveTo实现敌人素材:
代码:
Enemy.h#include “cocos2d.h”
USING_NS_CC;
class Enemy : public Sprite
{
public:
//通过随机设定Y轴坐标,初始化精灵球位置
virtual bool init(float positionY);
static Enemy* create(float positionY);
//精灵球精灵
Sprite *enemy;
//记录初始化Y轴位置
float p;
//记录屏幕大小
Size size;
//移除精灵球精灵
void rm();
};
Enemy.cpp
#include “Enemy.h”
USING_NS_CC;
Enemy* Enemy::create(float positionY)
{
Enemy *e = new Enemy();
e->init(positionY);
e->autorelease();
return e;
}
bool Enemy::init(float positionY)
{
Sprite::init();
size = Director::getInstance()->getVisibleSize();
p = positionY;
srand(time(NULL));
int i = rand()%3;
switch (i)
{
case 0:
{
enemy = Sprite::create(“e1.png”);
break;
}
case 1:
{
enemy = Sprite::create(“e2.png”);
break;
}
case 2:
{
enemy = Sprite::create(“e3.png”);
break;
}
}
enemy->setPosition(Point(size.width-50,p));
enemy->setPhysicsBody(PhysicsBody::createBox(enemy->getContentSize()));
enemy->getPhysicsBody()->setContactTestBitmask(1);
enemy->getPhysicsBody()->setTag(3);
enemy->runAction(Sequence::create(MoveTo::create(0.5f,Point(10,p)),CallFuncN::create(CC_CALLBACK_0(Enemy::rm,this)),NULL));
addChild(enemy);
return true;
}
void Enemy::rm()
{
enemy->removeFromParent();
}