上篇帖子写了敌人的创建,让我们的游戏感觉活泼了很多,今天要做的就是子弹的建立,子弹的建立其实跟敌人的建立差不多,只是一个是从左往右,一个是从右往左。
效果图
直接上代码,如果上面一篇文章你理解了,那么这一篇文章你也一定会理解的
SWGameBullet.h 和 SWGameBullet.cpp
SWGameBullet.h
//
// SWGameBullet.h
// Holdtail
//
// Created by 帅 印 on 13-12-31.
//
//
#ifndef __Holdtail__SWGameBullet__
#define __Holdtail__SWGameBullet__Holdtail
#include <iostream>
#include "cocos2d.h"
using namespace cocos2d;
class SWGameBullet : public cocos2d::Sprite{
public:
static SWGameBullet *createBullet(const char *_fileName,float _speed,Point _postion);
private:
//初始化函数
void bulletInit(float _speed,Point _posion);
void update(float time);
float speed;
virtual void onExit();
//是否已经运动
bool isActed;
};
#endif /* defined(__Holdtail__SWGameBullet__) */
SWGameBullet.cpp
//
// SWGameBullet.cpp
// Holdtail
//
// Created by 帅 印 on 13-12-31.
//
//
#include "SWGameBullet.h"
#include "SWGameEnemyPIG.h"
#include "SWGameWorld.h"
#include "cocos2d.h"
#include "SimpleAudioEngine.h"
using namespace CocosDenshion;
SWGameBullet * SWGameBullet::createBullet(const char *_fileName, float _speed, cocos2d::Point _postion){
SWGameBullet *bullet = new SWGameBullet();
if(bullet && bullet->initWithFile(_fileName)){
bullet->autorelease();
bullet->bulletInit(_speed, _postion);
return bullet;
}
CC_SAFE_DELETE(bullet);
return NULL;
}
void SWGameBullet::bulletInit(float _speed, cocos2d::Point _posion){
speed = _speed;
this->setPosition(_posion);
this->scheduleUpdate();
}
//生命周期
void SWGameBullet::onExit(){
this->unscheduleUpdate();
CCSprite::onExit();
}
//子弹逻辑
void SWGameBullet::update(float time){
//删除
if(this->getPositionX()>1500){
//从父类删除当前子弹
SWGameWorld::sharedWorld()->getArrayForBullet()->removeObject(this);
this->getParent()->removeChild(this,true);
}
isActed = true;
//子弹向又运动
this->setPosition(Point(this->getPosition() + Point(speed, 0)));
Array *array = SWGameWorld::sharedWorld()->getArrayForEnemy();
for (int i = 0; i<array->count(); i++) {
SWGameEnemyPIG *enemy = (SWGameEnemyPIG *)array->getObjectAtIndex(i);
if(enemy->boundingBox().intersectsRect(this->boundingBox())){
//爆炸粒子效果
ParticleSystemQuad *particle = CCParticleSystemQuad::create("particle_boom.plist");
particle->setPosition(enemy->getPosition());
particle->setAutoRemoveOnFinish(true);
SWGameWorld::sharedWorld()->addChild(particle);
//增加分数
//增加杀人数
//从敌人的数组将被攻击的敌怪删除
array->removeObject(enemy);
//删除子弹与敌怪
SWGameWorld::sharedWorld()->removeChild(enemy,true);
SWGameWorld::sharedWorld()->getArrayForBullet()->removeObject(this);
SWGameWorld::sharedWorld()->removeChild(this,true);
}
}
}
下面是下载源码的地址-->飞机直达