第一个cocos2dx游戏

想要制作一款打飞机的游戏,了解cocosdx和游戏制作,

第一次做游戏,水平有限。这个游戏差不多应该是最简单的了

一,建立一个菜单场景

1.新建一个cocos2dx游戏


2.再新建一个开始菜单场景 (因为没找到好的素材,就新建一个场景加一个按钮)

新建一个开始菜单场景,命名为GameMenu


3.在GameMenu.h文件中做一些函数的声明

#ifndef __Game__GameMenu__
#define __Game__GameMenu__

#include "cocos2d.h"

class GameMenu : public cocos2d::CCLayer//表示继承cocos2d 的CCLayer类
{
public:
    static cocos2d::CCScene* scene();//声明静态的 场景函数

    virtual bool init(); //初始化方法
    CREATE_FUNC(GameMenu);
    
    void playIsPressed(CCObject* pSender);//声明playIsPressed函数

};

#endif /* defined(__Game__GameMenu__) */

4.在 GameMenu.cpp中实现scene函数

CCScene* GameMenu::scene()
{
    CCScene *scene = CCScene::create();//创建场景
    GameMenu *layer = GameMenu::create();//创建菜单
    scene->addChild(layer); //将菜单添加到场景中
    return scene;
}
实现init函数

bool GameMenu::init()
{
    if ( !CCLayer::init() )
    {
        return false;
    }
    CCSize size = CCDirector::sharedDirector()->getWinSize();//取的屏幕的大小
    //创建图片精灵作为背景
    CCSprite *sp = CCSprite::create("background.jpg");//创建图片精灵
    sp->setPosition(ccp(size.width/2, size.height/2));//设置图片精灵的位置
    this->addChild(sp);//将图片精灵添加到场景中
    
    
    CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
                                                          "start.png",
                                                          "start.png",
                                                          this,
                                                          menu_selector(GameMenu::playIsPressed) );
    pCloseItem->setPosition( ccp(size.width/2, size.height/2) );
    CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);//创建菜单函数
    pMenu->setPosition( CCPointZero );
    
    this->addChild(pMenu, 1);

    return true;
}
实现playIsPressed函数

//作为菜单按钮的相应函数
void GameMenu::playIsPressed(CCObject* pSender)
{
    //转换到另一个场景中
    CCDirector::sharedDirector()->replaceScene(CCTransitionCrossFade::create(1.5, HelloWorld::scene()));
}
5.修改 AppDelegate.cpp让新建的场景作为进入app的场景



6.根据需求倒入函数

#include "SimpleAudioEngine.h"
#include "HelloWorldScene.h"
using namespace cocos2d;
using namespace CocosDenshion;


实现如下效果




二,定义几个精灵

(1)建立一个飞机

(2)建立子弹,让飞机可以打出子弹

(3)建立敌机,

由于下面代码有的调用了主场景类里的函数说一创建完,不能运行还会报不少错,需要创建完场景类才能正常运行。说明都在程序上注释着

1.建立一个飞机类,命名为player(首字母应该大写的,一开始弄错了)

实现player.h文件

#include "cocos2d.h"
using namespace cocos2d;
using namespace std;
class player:public cocos2d::CCSprite,public CCTouchDelegate//继承精灵  实现CCTouchDelegate协议
{
public:
    static player* createPlayer(const char* fileName);//定义createPlayer函数  可以调用本函数创建player
private:
    void playerInit(); //定义初始化方法
    virtual void onEnter();//本精灵创建 调用本函数
    virtual void onExit();//本精灵注销 调用本函数
    /*  相当于oc里面的
        -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event等函数
    */
    virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent);//TouchDelegate的协议函数
    virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent);
    virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent);

};
实现player.cpp

#include "player.h"
using namespace cocos2d;

player* player::createPlayer(const char* fileName)
{
    player *player = new class player();
    if (player&&player->initWithFile(fileName)) {
        player->autorelease();//自动管理内存
        player->playerInit();//调用初始化函数
        return player;
    }
    CC_SAFE_DELETE(player);
    return NULL;
    
}
void player::playerInit()
{
    //设置本精灵的初始化位置
    CCSize size = CCDirector::sharedDirector()->getWinSize();
    this->setPosition(ccp(size.width/2, this->getContentSize().height/2+10));
}

void player::onEnter()
{
    CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, true);
    //CCTouchDelegate指向本类
}
void player::onExit()
{
    CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
    //移除CCTouchDelegate协议
}
bool player::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
{
    this->setPosition(pTouch->getLocation());//本精灵的位置跟着手指移动
    return true;
}
void player::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent)
{
    this->setPosition(pTouch->getLocation());
}
void player::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent)
{
    this->setPosition(pTouch->getLocation());
}

这个类是自定义精灵

在场景中的调用方法为

    player *play =player::createPlayer("Spaceship.png");
    this->addChild(play, 1, 100);

2.制作子弹类,命名为 Bullet

实现Bullet.h

#include "cocos2d.h"
using namespace cocos2d;
class Bullet : public cocos2d::CCSprite//继承精灵
{
public:
    static Bullet* createBullet(const char* _fileName,float _speed,CCPoint _position);//创建子弹类
private:
    float speed;//速度变量
    void bulletInit(float _speed,CCPoint _position);//子弹初始化
    void update(float time);//刷新精灵函数
    virtual void onExit();//退出本精灵调用的函数
};

实现<span style="font-family: Menlo; font-size: 13px; ">Bullet.m</span>

#include "Bullet.h"
#include "HelloWorldScene.h"
#include "Enemy.h"
Bullet* Bullet::createBullet(const char* _fileName, float _speed, CCPoint _position)
{
    Bullet * bullet = new Bullet();
    if (bullet&&bullet->initWithFile(_fileName)) {
        bullet->autorelease();
        bullet->bulletInit(_speed, _position);
        return bullet;
    }
    CC_SAFE_DELETE(bullet);
    return NULL;
}
void Bullet::bulletInit(float _speed, CCPoint _position)
{
    speed=_speed;
    this->setPosition(_position);//初始化位置
    this->scheduleUpdate();//线程 中刷新本精灵
}
void Bullet::update(float time)
{
    //设置子弹的位置
    this->setPosition(ccpAdd(this->getPosition(), ccp(0, speed)));
    //取得主场景中的的敌机(这部分有的函数,是要在场景函数中实现的 )
    CCArray *array =HelloWorld::sharedWorld()->getArrayForEnemy();
    for (int i=0; i<array->count(); i++) {
        Enemy* enemy =(Enemy *) array->objectAtIndex(i);
        //判断子弹是否与敌机碰撞
        if (enemy->boundingBox().intersectsRect(this->boundingBox())) {
            //如果碰撞就通过cocos2dx的粒子效果制作爆炸效果(这个plist文件可以用ParticleDesigner软件制作)
            CCParticleSystemQuad *particle = CCParticleSystemQuad::create("boom.plist");
            particle->setPosition(enemy->getPosition());
            particle->setAutoRemoveOnFinish(true);
            HelloWorld::sharedWorld()->addChild(particle);
            //移除敌机和子弹
            array->removeObject(enemy);
            HelloWorld::sharedWorld()->removeChild(enemy,true);
            HelloWorld::sharedWorld()->removeChild(this,true);
        }
    }
    //子弹出界以后要消除
    if (this->getPositionY()<-(this->getContentSize().height)||this->getPositionY()>800) {
        this->getParent()->removeChild(this,true);
    }
}
void Bullet::onExit()
{
    //退出本精灵的时候 停止刷新线程
    this->unscheduleUpdate();
    CCSprite::onExit();
}


3.创建敌机类 命名为 Enemy
实现.h文件
#include "cocos2d.h"
using namespace cocos2d;
class Enemy :public cocos2d::CCSprite
{
public:
    static Enemy* createEnemy(const char* fileName,int _type);
private:
    void enemyInit(const char* fileName,int _type);
    void update(float time);
    
    bool isActed;
    int type;//可以定义敌机的类型
};

实现.cpp文件

#include "HelloWorldScene.h"
Enemy* Enemy::createEnemy(const char* fileName, int _type)
{
    Enemy* enemy = new Enemy();
    if (enemy&&enemy->initWithFile(fileName)) {
        enemy->autorelease();
        enemy->enemyInit(fileName, _type);
        return enemy;
    }
    CC_SAFE_DELETE(enemy);
    return NULL;
}
void Enemy::enemyInit(const char* fileName, int _type)
{
    type=_type;
    CCSize size = CCDirector::sharedDirector()->getWinSize();
    this->setPosition(ccp(((int)(CCRANDOM_0_1()*size.width))/65*65,this->getContentSize().height+size.height));
    //设置位置(在屏幕上随机)
    this->scheduleUpdate();
}

void Enemy::update(float time)
{
    this->setPosition(ccpAdd(this->getPosition(), ccp(0,-3)));
    //如果敌机出界移除
    if (this->getPositionY()<-(this->getContentSize().height)) {
        HelloWorld::sharedWorld()->getArrayForEnemy()->removeObject(this);
        this->getParent()->removeChild(this,true);
    }
}

三。设置主场景

将前面自定义的三个精灵,添加到战斗场景中

我直接是修改的系统上自带的HelloWorld类

实现HelloWorldScene.h

<span style="font-size: 14px; ">#include "cocos2d.h"
#include "player.h"
class HelloWorld : public cocos2d::CCLayer
{
public:
    virtual bool init();
    static HelloWorld *sharedWorld();
    static cocos2d::CCScene* scene();
    
    player* getPlayer();//获取飞机对象
    CCArray* getArrayForEnemy();//获取敌机数组(为判断碰撞准备)
    CREATE_FUNC(HelloWorld);
private:
    CCArray *arrayEnemy;//储存敌机的数组
    void autoCreateBullet();//创建子弹
    void autoCreateEnemy();//创建敌机
    virtual ~HelloWorld();
    
};
</span>
实现 HelloWorldScene.m

#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
#include "player.h"
#include "Bullet.h"
#include "Enemy.h"


#include <unistd.h>
using namespace cocos2d;
using namespace CocosDenshion;

static HelloWorld *sh;
HelloWorld * HelloWorld::sharedWorld()
{
    if (sh!=NULL) {
        return sh;
    }
    return NULL;
}
CCScene* HelloWorld::scene()
{
    // 'scene' is an autorelease object
    CCScene *scene = CCScene::create();
    
    // 'layer' is an autorelease object
    HelloWorld *layer = HelloWorld::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance2qa
bool HelloWorld::init()
{
    if ( !CCLayer::init() )
    {
        return false;
    }
    sh=this;
    arrayEnemy =CCArray::create();//初始化数组
    CC_SAFE_RETAIN(arrayEnemy);//内存管理方式
    
    player *play =player::createPlayer("Spaceship.png");//创建飞机对象
    this->addChild(play, 1, 100);
    
    this->schedule(schedule_selector(HelloWorld::autoCreateBullet), 0.37);
    this->schedule(schedule_selector(HelloWorld::autoCreateEnemy), 1);

    return true;
}
void HelloWorld::autoCreateEnemy()
{
    int randomCount = CCRANDOM_0_1()*5;
    for (int i=0; i<randomCount; i++) {
        Enemy* enemy = Enemy::createEnemy("Icon.png", 0);//创建敌人类
        arrayEnemy->addObject(enemy);
        this->addChild(enemy);
    }
}
void HelloWorld::autoCreateBullet()
{
    player *play = (player *)this->getChildByTag(100);//根据tag值获得飞机对象
    this->addChild(Bullet::createBullet("bullet.png", 2, ccpAdd(play->getPosition(), ccp(0, play->getContentSize().height*0.5))));//为飞机添加子弹
}
player* HelloWorld::getPlayer()
{
    player* play = (player*)HelloWorld::sharedWorld()->getChildByTag(100);
    return play;
}
CCArray* HelloWorld::getArrayForEnemy()
{
    return arrayEnemy;
}
HelloWorld::~HelloWorld()
{
    CC_SAFE_RELEASE(arrayEnemy);
}

添加上对应的图片就可以运行了(自己随便找的图片)






  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值