cocos2d-x 3.2 |飞机大战:飞机与子弹

cocos2d-x 3.2 |飞机大战:飞机与子弹
前情提要:飞机大战第二篇 实现飞机与子弹
如下: 新建类----->Plane + Bullet
第一步:飞机类
Plane.h
#include <stdio.h>
#include "cocos2d.h"
using namespace cocos2d;
//飞机方法
class Plane:public Node
{
public:
    CREATE_FUNC(Plane);//Creat 方法自动调用init
    float px, py;//坐标
    int hp;//血量
    bool init();//初始化
    void moveTo(int x, int y);//移动到x,y
};
Plane.cpp
bool Plane::init()
{
    //初始化方法
    if (!Node::init())
    {
        return false;
    }
    //初始化战机hp
    this->hp=3;
    
    //添加飞机图片
    auto fly1=Sprite::create("plane_3.png");
    this->addChild(fly1);
    fly1->setTag(10);
    
    return true;
}
void Plane::moveTo(int x, int y)
{
    this->getChildByTag(10)->setPosition(x,y);
    this->px=x;
    this->py=y;
}

第二步:子弹类
Bullet.h
#include <stdio.h>
#include "cocos2d.h"
using namespace cocos2d;

class Bullet:public Node
{
public:
    CREATE_FUNC(Bullet);

    int px,py;//坐标
    int type;//类型
    int level;//级别
    bool init();//初始化
    Sprite * bt;
    static Bullet * newBullet(int type, int level,int x,int y);//新子弹 类型 级别 坐标
    void moveTo(int x,int y);//移动子弹方法
};
Bullet.cpp
#include "Bullet.h"

bool Bullet::init()
{
    if (!Node::init()) {
        return false;
    }
    this->bt=nullptr;
    return true;
}
//创建子弹
Bullet * Bullet::newBullet(int type, int level,int x,int y)
{
    //创建新的子弹
    Bullet * newBullet=Bullet::create();
    
    
    switch (type) {
        case 1://普通光弹
            newBullet->bt=Sprite::create("bullet_1.png",Rect(0,0,20,60));
            break;
        case 2://炮弹
            newBullet->bt=Sprite::create("bullet_2.png",Rect(0,0,24,76));
            break;
        case 3://激光弹
            break;
    }
    newBullet->addChild(newBullet->bt);
    newBullet->moveTo(x, y);
    return newBullet;
}
void Bullet::moveTo(int x,int y)
{
    this->bt->setPosition(Vec2(x,y));
    this->px=x;
    this->py=y;
    
}


总结:创建我方战机+子弹类

你可能感兴趣的:(类,创建,飞机,飞机大战,子弹)