从零开始学习cocoStudio(4)--背包功能

背包基本功能:


    1.存放物品

    2.穿戴装备(套装、武器、宠物等)

    3.待定功能(出售、合成、排序)


如图:


从零开始学习cocoStudio(4)--背包功能


    在做此功能先,要先在AppDelegate类添加搜索资源目录,否则会因资源问题导致各种崩~~~


AppDelegate.cpp

bool AppDelegate::applicationDidFinishLaunching() {
    // initialize director
    CCDirector* pDirector = CCDirector::sharedDirector();
    CCEGLView* pEGLView = CCEGLView::sharedOpenGLView();

    pDirector->setOpenGLView(pEGLView);
	
    // turn on display FPS
   // pDirector->setDisplayStats(true);

    // set FPS. the default value is 1.0/60 if you don‘t call this
    pDirector->setAnimationInterval(1.0 / 60);

    
    CCSize screenSize = CCEGLView::sharedOpenGLView()->getFrameSize();
    
    CCSize designSize = CCSizeMake(480, 320);
    
    CCFileUtils* pFileUtils = CCFileUtils::sharedFileUtils();
    
    if (screenSize.height > 320)
    {
        CCSize resourceSize = CCSizeMake(960, 640);
        std::vector<std::string> searchPaths;
        searchPaths.push_back("hd");
        pFileUtils->setSearchPaths(searchPaths);
        pDirector->setContentScaleFactor(resourceSize.height/designSize.height);
    }
    
    CCEGLView::sharedOpenGLView()->setDesignResolutionSize(designSize.width, designSize.height, kResolutionShowAll);

    CocosGUIExamplesEquipScene *pScene = new CocosGUIExamplesEquipScene();
    pScene->autorelease();
    
    // run
    pDirector->runWithScene(pScene);
    
    
    
    // create a scene. it‘s an autorelease object
//    CCScene *pScene = HelloWorld::scene();
//
//    // run
//    pDirector->runWithScene(pScene);

    return true;
}
背包类

CocosGUIExamplesEquipScene.h

#ifndef __DemoBag__CocosGUIExamplesEquipScene__
#define __DemoBag__CocosGUIExamplesEquipScene__

#include <iostream>

#include "cocos2d.h"
#include "cocos-ext.h"
//#include "../../testBasic.h"

#define EQUIP_LAYOUT_TAG_ROOT                            1000       //背包主目录
#define EQUIP_LAYOUT_TAG_UP                              1001       //背包层
#define EQUIP_LAYOUT_TAG_CLOTHES                         1002       //装备层
#define EQUIP_LAYOUT_TAG_WEAPONS                         1003       //武器层
#define EQUIP_LAYOUT_TAG_PETS                            1004       //宠物层

#define EQUIP_SWITCH_LAYOUT_BUTTON_TAG_CLOTHES           1005       //装备按钮
#define EQUIP_SWITCH_LAYOUT_BUTTON_TAG_WEAPONS           1006       //武器按钮
#define EQUIP_SWITCH_LAYOUT_BUTTON_TAG_PETS              1007       //宠物按钮


USING_NS_CC;
USING_NS_CC_EXT;
using namespace gui;

class CocosGUIExamplesEquipScene : public CCScene
{
public:
    CocosGUIExamplesEquipScene();
    ~CocosGUIExamplesEquipScene();
    
    
    void EquipInit();
    
    virtual void onEnter();
    virtual void onExit();

    void switchBtnCallBack(CCObject* pSender);          //菜单切换(装备、武器、宠物)
    
    void create();                                      //初始化装备
    void createClothes();                               //创建装备
    void createWeapons();                               //创建武器
    void createPets();                                  //创建宠物
    
    void touch(CCObject* pSender);                      // 按下
    void move(CCObject* pSender);                       // 移动
    void drop(CCObject* pSender);                       // 取消
    
    void touchEvent(CCObject *pSender, TouchEventType type);    //点击事件
    void backOver(CCObject *pObject);                           //返回事件
    
    void menuCloseCallback(CCObject* pSender);                  //退了按钮
    
protected:
    enum EQUIP_TYPE
    {
        EQUIP_TYPE_NONE,        //默认
        EQUIP_TYPE_CLOTHES,     //装备
        EQUIP_TYPE_WEAPONS,     //武器
        EQUIP_TYPE_PETS,        //宠物
    };
    
protected:
    UILayer* m_pUIlayer;
    
    //装备
    EQUIP_TYPE m_eEquipType;        //宏(装备、武器、宠物)
    
    CCDictionary* m_dicBeUsedSlot;  //存储上装容器(框)
    CCDictionary* m_dicClothesSlot; //存储装备容器(框)
    CCDictionary* m_dicWeaponsSlot; //存储武器容器(框)
    CCDictionary* m_dicPetsSlot;    //存储宠物容器(框)
    
    CCDictionary* m_dicClothes;     //存储装备容器(图片)
    CCDictionary* m_dicWeapons;     //存储武器容器(图片)
    CCDictionary* m_dicPets;        //存储宠物容器(图片)

    
    int container_1_Zorder;         //装备层级(Z轴)
    int container_2_Zorder;         //武器层级(Z轴)
    int container_3_Zorder;         //宠物层级(Z轴)
    
    CCPoint container_1_Position;   //装备位置
    CCPoint container_2_Position;   //装备位置
    CCPoint container_3_Position;   //装备位置
    
    CCPoint movePoint;              //移动始点
    CCPoint lastPoint;              //移动终点
    
    CCPoint widgetLastWorldSpace;   //游戏世界坐标(始点)
    CCPoint widgetLastNodeSpace;    //节点位置
    UIWidget* lastWidgetParent;     //获得父节点
};

#endif /* defined(__DemoBag__CocosGUIExamplesEquipScene__) */
CocosGUIExamplesEquipScene.cpp

#include "CocosGUIExamplesEquipScene.h"

CocosGUIExamplesEquipScene::CocosGUIExamplesEquipScene()
{
    CCScene::init();
}

CocosGUIExamplesEquipScene::~CocosGUIExamplesEquipScene()
{
    
}

void CocosGUIExamplesEquipScene::onEnter()
{
    CCScene::onEnter();
    
    m_pUIlayer = UILayer::create();
    m_pUIlayer->scheduleUpdate();
    addChild(m_pUIlayer);
    
    //背包初始化
    EquipInit();
    
    // 退出按钮
    UIButton* exit_button = UIButton::create();
    exit_button->setTouchEnabled(true);
    exit_button->loadTextures("CloseNormal.png", "CloseSelected.png", "");
    exit_button->setPosition(ccp(m_pUIlayer->getContentSize().width - exit_button->getContentSize().width, exit_button->getContentSize().height));
    exit_button->addTouchEventListener(this, toucheventselector(CocosGUIExamplesEquipScene::menuCloseCallback));
    m_pUIlayer->addWidget(exit_button);
}

void CocosGUIExamplesEquipScene::onExit()
{
    
}

//背包初始化
void CocosGUIExamplesEquipScene::EquipInit()
{
    m_eEquipType = EQUIP_TYPE_CLOTHES;
    
    m_dicBeUsedSlot = CCDictionary::create();
    CC_SAFE_RETAIN(m_dicBeUsedSlot);
    m_dicClothesSlot = CCDictionary::create();
    CC_SAFE_RETAIN(m_dicClothesSlot);
    m_dicWeaponsSlot = CCDictionary::create();
    CC_SAFE_RETAIN(m_dicWeaponsSlot);
    m_dicPetsSlot = CCDictionary::create();
    CC_SAFE_RETAIN(m_dicPetsSlot);
    
    
    m_dicClothes = CCDictionary::create();
    CC_SAFE_RETAIN(m_dicClothes);
    m_dicWeapons = CCDictionary::create();
    CC_SAFE_RETAIN(m_dicWeapons);
    m_dicPets = CCDictionary::create();
    CC_SAFE_RETAIN(m_dicPets);
    
    container_1_Zorder = 0;
    container_2_Zorder = 0;
    container_3_Zorder = 0;
    container_1_Position = CCPointZero;  
    container_2_Position = CCPointZero;
    container_3_Position = CCPointZero;
    movePoint = CCPointZero;
    lastPoint = CCPointZero;
    
    widgetLastWorldSpace = CCPointZero;
    widgetLastNodeSpace = CCPointZero;
    lastWidgetParent = NULL;

    
    //导入背包UI
    Layout* equipe_root = dynamic_cast<Layout*>(GUIReader::shareReader()->widgetFromJsonFile("cocosgui/gui_examples/equip_1/equip_1.json"));
    equipe_root->setTag(EQUIP_LAYOUT_TAG_ROOT);
    m_pUIlayer->addWidget(equipe_root);
    
    // title layout
    Layout* title_layout = dynamic_cast<Layout*>(equipe_root->getChildByName("title_panel"));
    
    //关闭按钮
    UIButton* close_btn = dynamic_cast<UIButton*>(title_layout->getChildByName("close_button"));
    close_btn->setVisible(false);
    
    // up layout
    Layout* up_layout = dynamic_cast<Layout*>(equipe_root->getChildByName("up_panel"));
    up_layout->setTag(EQUIP_LAYOUT_TAG_UP);
    
    //切换按钮(装备、武器、宠物)
    //装备
    UITextButton* clothes_btn = dynamic_cast<UITextButton*>(up_layout->getChildByName("clothes_button"));
    clothes_btn->addTouchEventListener(this, toucheventselector(CocosGUIExamplesEquipScene::switchBtnCallBack));
    clothes_btn->setTag(EQUIP_SWITCH_LAYOUT_BUTTON_TAG_CLOTHES);
    clothes_btn->setBright(false);  //设置无效灰色

    //武器
    UITextButton* weapons_btn = dynamic_cast<UITextButton*>(up_layout->getChildByName("weapons_button"));
    weapons_btn->addTouchEventListener(this, toucheventselector(CocosGUIExamplesEquipScene::switchBtnCallBack));
    weapons_btn->setTag(EQUIP_SWITCH_LAYOUT_BUTTON_TAG_WEAPONS);
    
    //宠物
    UITextButton* pets_btn = dynamic_cast<UITextButton*>(up_layout->getChildByName("pets_button"));
    pets_btn->addTouchEventListener(this, toucheventselector(CocosGUIExamplesEquipScene::switchBtnCallBack));
    pets_btn->setTag(EQUIP_SWITCH_LAYOUT_BUTTON_TAG_PETS);
    
    // repertories
    // 装备 layout
    Layout* clothes_layout = dynamic_cast<Layout*>(equipe_root->getChildByName("clothes_panel"));
    clothes_layout->setTag(EQUIP_LAYOUT_TAG_CLOTHES);
    
    // 武器 layout
    Layout* weapons_layout = dynamic_cast<Layout*>(equipe_root->getChildByName("weapons_panel"));
    weapons_layout->setTag(EQUIP_LAYOUT_TAG_WEAPONS);
    
    // 宠物 layout
    Layout* pets_layout = dynamic_cast<Layout*>(equipe_root->getChildByName("pets_panel"));
    pets_layout->setTag(EQUIP_LAYOUT_TAG_PETS);
    
    container_1_Zorder = clothes_layout->getZOrder();
    container_2_Zorder = weapons_layout->getZOrder();
    container_3_Zorder = pets_layout->getZOrder();
    
    container_1_Position = clothes_layout->getPosition();
    container_2_Position = weapons_layout->getPosition();
    container_3_Position = pets_layout->getPosition();

    //默认显示衣服
    clothes_layout->setVisible(true);
    weapons_layout->setVisible(false);
    pets_layout->setVisible(false);
    
    CCObject* obj = NULL;
    // clothes repertory slot
    CCARRAY_FOREACH(clothes_layout->getChildren(), obj)
    {
        UIWidget* child = dynamic_cast<UIWidget*>(obj);
        m_dicClothesSlot->setObject(child, child->getName());
    }
    // weapons repertory slot
    CCARRAY_FOREACH(weapons_layout->getChildren(), obj)
    {
        UIWidget* child = dynamic_cast<UIWidget*>(obj);
        m_dicWeaponsSlot->setObject(child, child->getName());
    }
    // pets repertory slot
    CCARRAY_FOREACH(pets_layout->getChildren(), obj)
    {
        UIWidget* child = dynamic_cast<UIWidget*>(obj);
        m_dicPetsSlot->setObject(child, child->getName());
    }
    
    // actor
    UIImageView* wallBG_iv = dynamic_cast<UIImageView*>(up_layout->getChildByName("wall"));
    UIImageView* wal_iv = UIImageView::create();
    wal_iv->loadTexture("cocosgui/gui_examples/equip_1/equip/eg/Haven_Alaric.png");         //英雄头像
    wal_iv->setAnchorPoint(ccp(0.5, 0.5));
    wal_iv->setScale(0.76);
    float wal_x = wallBG_iv->getSize().width / 2.04;
    float wal_y = wallBG_iv->getSize().height / 2.4;
    wal_iv->setPosition(ccp((-wallBG_iv->getSize().width / 2) +  wal_x,
                            (-wallBG_iv->getSize().height / 2) + wal_y));
    wallBG_iv->addChild(wal_iv);
    
    
    //默认上装位置
    UIImageView* originalClothesSlot_iv = dynamic_cast<UIImageView*>(up_layout->getChildByName("1"));
    UIImageView* originalClothes_iv = UIImageView::create();
    originalClothes_iv->loadTexture("cocosgui/gui_examples/equip_1/equip/eg/6.png");
    originalClothes_iv->setScale(0.3);
    originalClothesSlot_iv->addChild(originalClothes_iv);
    m_dicBeUsedSlot->setObject(originalClothesSlot_iv, originalClothesSlot_iv->getName());

    UIImageView* slot_2_iv = dynamic_cast<UIImageView*>(up_layout->getChildByName("2"));
    m_dicBeUsedSlot->setObject(slot_2_iv, slot_2_iv->getName());
    UIImageView* slot_3_iv = dynamic_cast<UIImageView*>(up_layout->getChildByName("3"));
    m_dicBeUsedSlot->setObject(slot_3_iv, slot_3_iv->getName());
    UIImageView* slot_4_iv = dynamic_cast<UIImageView*>(up_layout->getChildByName("4"));
    m_dicBeUsedSlot->setObject(slot_4_iv, slot_4_iv->getName());
    UIImageView* slot_5_iv = dynamic_cast<UIImageView*>(up_layout->getChildByName("5"));
    m_dicBeUsedSlot->setObject(slot_5_iv, slot_5_iv->getName());
    UIImageView* slot_6_iv = dynamic_cast<UIImageView*>(up_layout->getChildByName("6"));
    m_dicBeUsedSlot->setObject(slot_6_iv, slot_6_iv->getName());
    
    //背包(装备、武器、宠物)初始化
    create();
}

void CocosGUIExamplesEquipScene::create()
{
    createClothes();
    createWeapons();
    createPets();
}


void CocosGUIExamplesEquipScene::createClothes()
{
    Layout* clothes_layout = dynamic_cast<Layout*>(m_pUIlayer->getWidgetByTag(EQUIP_LAYOUT_TAG_CLOTHES));
    
    // clothes
    float parent_w = clothes_layout->getSize().width;
    float parent_h = clothes_layout->getSize().height;
    float offest_x = parent_w / 10;
    float offest_y = parent_h / 6;
    
    const short columnMax = 3;
    
    // jacket
    const char* jacket_png[columnMax] =
    {
        "cocosgui/gui_examples/equip_1/equip/eg/Clothes/3.png",
        "cocosgui/gui_examples/equip_1/equip/eg/Clothes/4.png",
        "cocosgui/gui_examples/equip_1/equip/eg/Clothes/5.png",
    };
    const char* jacket_name[columnMax] =
    {
        "jacket_taenia",
        "jacket_suit",
        "jacket_shoes",
    };
    // jacket imageview add to clothes slot
    for (int i = 0; i < columnMax; ++i)
    {
        UIImageView* jacket_iv = UIImageView::create();
        jacket_iv->loadTexture(jacket_png[i]);
        jacket_iv->setScale(0.3);
        jacket_iv->setAnchorPoint(ccp(0.5, 0.5));
        jacket_iv->setPosition(ccp(offest_x + i * offest_x * 4, parent_h - offest_y));
        UIWidget* lastChild = dynamic_cast<UIWidget*>(clothes_layout->getChildren()->lastObject());
        if (lastChild)
        {
            jacket_iv->setZOrder(lastChild->getZOrder() + 1);
        }
        jacket_iv->setName(jacket_name[i]);
        jacket_iv->setTouchEnabled(true);
        jacket_iv->setScale(0.3);
        jacket_iv->addTouchEventListener(this, toucheventselector(CocosGUIExamplesEquipScene::touchEvent));
        
        
        CCObject* obj = NULL;
        CCARRAY_FOREACH(clothes_layout->getChildren(), obj)
        {
            UIWidget* slot = dynamic_cast<UIWidget*>(obj);
            slot->setCascadeColorEnabled(false);
            if (slot->boundingBox().containsPoint(jacket_iv->getPosition()))
            {
                jacket_iv->setPosition(CCPointZero);
                slot->addChild(jacket_iv);
                break;
            }
        }
        
        m_dicClothes->setObject(jacket_iv, jacket_iv->getName());
    }
    
    // kimono
    const char* kimono_png[columnMax] =
    {
        "cocosgui/gui_examples/equip_1/equip/eg/Clothes/8.png",
        "cocosgui/gui_examples/equip_1/equip/eg/Clothes/10.png",
        "cocosgui/gui_examples/equip_1/equip/eg/Clothes/9.png",
    };
    const char* kimono_name[columnMax] =
    {
        "kimono_strawhat",
        "kimono_suit",
        "kimono_shoes",
    };
    // kimono imageview add to clothes slot
    for (int i = 0; i < columnMax; ++i)
    {
        UIImageView* kimono_iv = UIImageView::create();
        kimono_iv->loadTexture(kimono_png[i]);
        kimono_iv->setScale(0.3);
        kimono_iv->setPosition(ccp(offest_x + i * offest_x * 4, parent_h - offest_y * 3));
        UIWidget* lastChild = dynamic_cast<UIWidget*>(clothes_layout->getChildren()->lastObject());
        if (lastChild)
        {
            kimono_iv->setZOrder(lastChild->getZOrder() + 1);
        }
        kimono_iv->setName(kimono_name[i]);
        kimono_iv->setTouchEnabled(true);
        kimono_iv->addTouchEventListener(this, toucheventselector(CocosGUIExamplesEquipScene::touchEvent));

        CCObject* obj = NULL;
        CCARRAY_FOREACH(clothes_layout->getChildren(), obj)
        {
            UIWidget* slot = dynamic_cast<UIWidget*>(obj);
            slot->setCascadeColorEnabled(false);
            if (slot->boundingBox().containsPoint(kimono_iv->getPosition()))
            {
                kimono_iv->setPosition(CCPointZero);
                slot->addChild(kimono_iv);
                break;
            }
        }
    
        m_dicClothes->setObject(kimono_iv, kimono_iv->getName());
    }
}

void CocosGUIExamplesEquipScene::createWeapons()
{
    Layout* weapons_panel = dynamic_cast<Layout*>(m_pUIlayer->getWidgetByTag(EQUIP_LAYOUT_TAG_WEAPONS));
    
    // weapons
    float parent_w = weapons_panel->getSize().width;
    float parent_h = weapons_panel->getSize().height;
    float offest_x = parent_w / 10;
    float offest_y = parent_h / 6;
    
    // sword
    const short swordAmount = 3;
    const char* sword_png[swordAmount] =
    {
        "cocosgui/gui_examples/equip_1/equip/eg/weapons/train.png",
        "cocosgui/gui_examples/equip_1/equip/eg/weapons/research.png",
        "cocosgui/gui_examples/equip_1/equip/eg/weapons/upgrade.png",
    };
    const char* sword_name[swordAmount] =
    {
        "sword_sword",
        "sword_plus",
        "sword_hammer",
    };
    
    // sword imageview add to weapons slot
    for (int i = 0; i < swordAmount; ++i)
    {
        UIImageView* sword_iv = UIImageView::create();
        sword_iv->loadTexture(sword_png[i]);
        sword_iv->setScale(0.3);
        sword_iv->setPosition(ccp(offest_x, parent_h - offest_y - i * (offest_y * 2)));
        UIWidget* lastChild = dynamic_cast<UIWidget*>(weapons_panel->getChildren()->lastObject());
        if (lastChild)
        {
            sword_iv->setZOrder(lastChild->getZOrder() + 1);
        }
        sword_iv->setName(sword_name[i]);
        sword_iv->setScale(0.3);
        sword_iv->addTouchEventListener(this, toucheventselector(CocosGUIExamplesEquipScene::touchEvent));
        
        CCObject* obj = NULL;
        CCARRAY_FOREACH(weapons_panel->getChildren(), obj)
        {
            UIWidget* slot = dynamic_cast<UIWidget*>(obj);
            slot->setCascadeColorEnabled(false);
            if (slot->boundingBox().containsPoint(sword_iv->getPosition()))
            {
                sword_iv->setPosition(CCPointZero);
                slot->addChild(sword_iv);
                break;
            }
        }
        
        m_dicWeapons->setObject(sword_iv, sword_iv->getName());
    }
    

    // arrow
    const short arrowAmount = 3;
    const char* arrow_png[arrowAmount] =
    {
        "cocosgui/gui_examples/equip_1/equip/eg/weapons/shop_shield_1.png",
        "cocosgui/gui_examples/equip_1/equip/eg/weapons/shop_shield_2.png",
        "cocosgui/gui_examples/equip_1/equip/eg/weapons/shop_shield_3.png",
    };
    const char* arrow_name[arrowAmount] =
    {
        "arraw_normal",
        "arraw_hard",
        "arraw_devil",
    };
    // arrow imageview add to weapons slot
    for (int i = 0; i < arrowAmount; ++i)
    {
        UIImageView* arrow_iv = UIImageView::create();
        arrow_iv->loadTexture(arrow_png[i]);
        arrow_iv->setScale(0.16);
        arrow_iv->setPosition(ccp(offest_x * 5, parent_h - offest_y - i * (offest_y * 2)));
        UIWidget* lastChild = dynamic_cast<UIWidget*>(weapons_panel->getChildren()->lastObject());
        if (lastChild)
        {
            arrow_iv->setZOrder(lastChild->getZOrder() + 1);
        }
        arrow_iv->setName(arrow_name[i]);
        arrow_iv->addTouchEventListener(this, toucheventselector(CocosGUIExamplesEquipScene::touchEvent));
        
        
        CCObject* obj = NULL;
        CCARRAY_FOREACH(weapons_panel->getChildren(), obj)
        {
            UIWidget* slot = dynamic_cast<UIWidget*>(obj);
            slot->setCascadeColorEnabled(false);
            if (slot->boundingBox().containsPoint(arrow_iv->getPosition()))
            {
                arrow_iv->setPosition(CCPointZero);
                slot->addChild(arrow_iv);
                break;
            }
        }
        
        m_dicWeapons->setObject(arrow_iv, arrow_iv->getName());
    }
    
    // bomb
    const short bombAmount = 1;
    const char* bomb_png[bombAmount] =
    {
        "cocosgui/gui_examples/equip_1/equip/eg/weapons/sell.png",
    };
    const char* bomb_name[bombAmount] =
    {
        "bomb_normal",
    };
    // bomo imageview add to weapons slot
    for (int i = 0; i < bombAmount; ++i)
    {
        UIImageView* bomb_iv = UIImageView::create();
        bomb_iv->loadTexture(bomb_png[i]);
        bomb_iv->setScale(0.3);
        bomb_iv->setPosition(ccp(offest_x * 9, parent_h - offest_y - i * (offest_y * 2)));
        UIWidget* lastChild = dynamic_cast<UIWidget*>(weapons_panel->getChildren()->lastObject());
        if (lastChild)
        {
            bomb_iv->setZOrder(lastChild->getZOrder() + 1);
        }
        bomb_iv->setName(bomb_name[i]);
        bomb_iv->addTouchEventListener(this, toucheventselector(CocosGUIExamplesEquipScene::touchEvent));
        
        CCObject* obj = NULL;
        CCARRAY_FOREACH(weapons_panel->getChildren(), obj)
        {
            UIWidget* slot = dynamic_cast<UIWidget*>(obj);
            slot->setCascadeColorEnabled(false);
            if (slot->boundingBox().containsPoint(bomb_iv->getPosition()))
            {
                bomb_iv->setPosition(CCPointZero);
                slot->addChild(bomb_iv);
                break;
            }
        }
        
        m_dicWeapons->setObject(bomb_iv, bomb_iv->getName());
    }
}

void CocosGUIExamplesEquipScene::createPets()
{
    Layout* pets_layout = dynamic_cast<Layout*>(m_pUIlayer->getWidgetByTag(EQUIP_LAYOUT_TAG_PETS));
    
    // pets
    float parent_w = pets_layout->getSize().width;
    float parent_h = pets_layout->getSize().height;
    float offest_x = parent_w / 10;
    float offest_y = parent_h / 6;
    
    // dragon
    const short dragonAmount = 1;
    const char* dragon_png[dragonAmount] =
    {
        "cocosgui/gui_examples/equip_1/equip/eg/pets/7.png",
    };
    const char* dragon_name[dragonAmount] =
    {
        "pet_dragon",
    };
    // dragon imageview add to pets slot
    for (int i = 0; i < dragonAmount; ++i)
    {
        UIImageView* dragon_iv = UIImageView::create();
        dragon_iv->loadTexture(dragon_png[i]);
        dragon_iv->setPosition(ccp(offest_x, parent_h - offest_y - i * (offest_y * 2)));
        UIWidget* lastChild = dynamic_cast<UIWidget*>(pets_layout->getChildren()->lastObject());
        if (lastChild)
        {
            dragon_iv->setZOrder(lastChild->getZOrder() + 1);
        }
        dragon_iv->setName(dragon_name[i]);
        dragon_iv->addTouchEventListener(this, toucheventselector(CocosGUIExamplesEquipScene::touchEvent));
        dragon_iv->setScale(0.18);
        
        CCObject* obj = NULL;
        CCARRAY_FOREACH(pets_layout->getChildren(), obj)
        {
            UIWidget* slot = dynamic_cast<UIWidget*>(obj);
            slot->setCascadeColorEnabled(false);
            if (slot->boundingBox().containsPoint(dragon_iv->getPosition()))
            {
                dragon_iv->setPosition(CCPointZero);
                slot->addChild(dragon_iv);
                break;
            }
        }
        
        m_dicPets->setObject(dragon_iv, dragon_iv->getName());
    }
    
    // crab
    const short crabAmount = 1;
    const char* crab_png[crabAmount] =
    {
        "cocosgui/gui_examples/equip_1/equip/eg/pets/crab.png",
    };
    const char* crab_name[crabAmount] =
    {
        "pet_crab",
    };
    // crab imageview add to pets slot
    for (int i = 0; i < crabAmount; ++i)
    {
        UIImageView* crab_iv = UIImageView::create();
        crab_iv->loadTexture(crab_png[i]);
        crab_iv->setScale(0.18);
        crab_iv->setPosition(ccp(offest_x * 5, parent_h - offest_y - i * (offest_y * 2)));
        UIWidget* lastChild = dynamic_cast<UIWidget*>(pets_layout->getChildren()->lastObject());
        if (lastChild)
        {
            crab_iv->setZOrder(lastChild->getZOrder() + 1);
        }
        crab_iv->setName(crab_name[i]);
        crab_iv->setScale(0.18);
        crab_iv->addTouchEventListener(this, toucheventselector(CocosGUIExamplesEquipScene::touchEvent));
        
        CCObject* obj = NULL;
        CCARRAY_FOREACH(pets_layout->getChildren(), obj)
        {
            UIWidget* slot = dynamic_cast<UIWidget*>(obj);
            slot->setCascadeColorEnabled(false);
            if (slot->boundingBox().containsPoint(crab_iv->getPosition()))
            {
                crab_iv->setPosition(CCPointZero);
                slot->addChild(crab_iv);
                break;
            }
        }
        
        m_dicPets->setObject(crab_iv, crab_iv->getName());
    }

}


void CocosGUIExamplesEquipScene::switchBtnCallBack(cocos2d::CCObject *pSender)
{
    //CCLOG("有感觉");
    // switch button
    UIButton* button = dynamic_cast<UIButton*>(pSender);
    
    // equip root
    Layout* root = dynamic_cast<Layout*>(m_pUIlayer->getWidgetByTag(EQUIP_LAYOUT_TAG_ROOT));
    
    // equip repertory
    Layout* clothes_layout = dynamic_cast<Layout*>(root->getChildByTag(EQUIP_LAYOUT_TAG_CLOTHES));
    Layout* weapons_layout = dynamic_cast<Layout*>(root->getChildByTag(EQUIP_LAYOUT_TAG_WEAPONS));
    Layout* pets_layout = dynamic_cast<Layout*>(root->getChildByTag(EQUIP_LAYOUT_TAG_PETS));
    
    Layout* up_layout = dynamic_cast<Layout*>(root->getChildByTag(EQUIP_LAYOUT_TAG_UP));
    UITextButton* clothes_btn = dynamic_cast<UITextButton*>(up_layout->getChildByTag(EQUIP_SWITCH_LAYOUT_BUTTON_TAG_CLOTHES));
    UITextButton* weapons_btn = dynamic_cast<UITextButton*>(up_layout->getChildByTag(EQUIP_SWITCH_LAYOUT_BUTTON_TAG_WEAPONS));
    UITextButton* pets_btn = dynamic_cast<UITextButton*>(up_layout->getChildByTag(EQUIP_SWITCH_LAYOUT_BUTTON_TAG_PETS));
    
    clothes_btn->visit();
    weapons_btn->visit();
    pets_btn->visit();
    
    CCDictElement* element = NULL;

    // switch slot
    switch (button->getTag())
    {
        case EQUIP_SWITCH_LAYOUT_BUTTON_TAG_CLOTHES:
        {
            m_eEquipType = EQUIP_TYPE_CLOTHES;
            
            //clothes_btn->disable();
            
            clothes_btn->setBright(false);
            weapons_btn->setBright(true);
            pets_btn->setBright(true);
            
            //显示装备层
            clothes_layout->setVisible(true);
            weapons_layout->setVisible(false);
            pets_layout->setVisible(false);
            
            
            clothes_layout->setZOrder(container_1_Zorder);
            weapons_layout->setZOrder(container_2_Zorder);
            pets_layout->setZOrder(container_3_Zorder);
            
            clothes_layout->setPosition(container_1_Position);
            weapons_layout->setPosition(container_2_Position);
            pets_layout->setPosition(container_3_Position);
            
            // equip slot touch able
            clothes_layout->setTouchEnabled(true);
            CCDICT_FOREACH(m_dicClothesSlot, element)
            {
                UIWidget* child = dynamic_cast<UIWidget*>(element->getObject());
                child->setTouchEnabled(true);
            }
            CCDICT_FOREACH(m_dicClothes, element)
            {
                UIWidget* child = dynamic_cast<UIWidget*>(element->getObject());
                child->setTouchEnabled(true);
            }
            weapons_layout->setTouchEnabled(false);
            CCDICT_FOREACH(m_dicWeaponsSlot, element)
            {
                UIWidget* child = dynamic_cast<UIWidget*>(element->getObject());
                child->setTouchEnabled(false);
            }
            CCDICT_FOREACH(m_dicWeapons, element)
            {
                UIWidget* child = dynamic_cast<UIWidget*>(element->getObject());
                child->setTouchEnabled(false);
            }
            pets_layout->setTouchEnabled(false);
            CCDICT_FOREACH(m_dicPetsSlot, element)
            {
                UIWidget* child = dynamic_cast<UIWidget*>(element->getObject());
                child->setTouchEnabled(false);
            }
            CCDICT_FOREACH(m_dicPets, element)
            {
                UIWidget* child = dynamic_cast<UIWidget*>(element->getObject());
                child->setTouchEnabled(false);
            }
        }
            break;
            
        case EQUIP_SWITCH_LAYOUT_BUTTON_TAG_WEAPONS:
        {
            m_eEquipType = EQUIP_TYPE_WEAPONS;

            clothes_btn->setBright(true);
            weapons_btn->setBright(false);
            pets_btn->setBright(true);
            
            //显示武器层
            clothes_layout->setVisible(false);
            weapons_layout->setVisible(true);
            pets_layout->setVisible(false);
            
            clothes_layout->setZOrder(container_3_Zorder);
            weapons_layout->setZOrder(container_1_Zorder);
            pets_layout->setZOrder(container_2_Zorder);
            
            weapons_layout->setPosition(container_1_Position);
            pets_layout->setPosition(container_2_Position);
            clothes_layout->setPosition(container_3_Position);
            
            // equip slot touch able
            weapons_layout->setBright(true);
            CCDICT_FOREACH(m_dicWeaponsSlot, element)
            {
                UIWidget* child = dynamic_cast<UIWidget*>(element->getObject());
                child->setTouchEnabled(true);
            }
            CCDICT_FOREACH(m_dicWeapons, element)
            {
                UIWidget* child = dynamic_cast<UIWidget*>(element->getObject());
                child->setTouchEnabled(true);
            }
            clothes_layout->setTouchEnabled(false);
            CCDictElement* element = NULL;
            CCDICT_FOREACH(m_dicClothesSlot, element)
            {
                UIWidget* child = dynamic_cast<UIWidget*>(element->getObject());
                child->setTouchEnabled(false);
            }
            CCDICT_FOREACH(m_dicClothes, element)
            {
                UIWidget* child = dynamic_cast<UIWidget*>(element->getObject());
                child->setTouchEnabled(false);
            }
            pets_layout->setTouchEnabled(false);
            CCDICT_FOREACH(m_dicPetsSlot, element)
            {
                UIWidget* child = dynamic_cast<UIWidget*>(element->getObject());
                child->setTouchEnabled(false);
            }
            CCDICT_FOREACH(m_dicPets, element)
            {
                UIWidget* child = dynamic_cast<UIWidget*>(element->getObject());
                child->setTouchEnabled(false);
            }
        }
            break;
            
        case EQUIP_SWITCH_LAYOUT_BUTTON_TAG_PETS:
        {
            m_eEquipType = EQUIP_TYPE_PETS;
            
            clothes_btn->setBright(true);
            weapons_btn->setBright(true);
            pets_btn->setBright(false);
            
            //显示宠物层
            clothes_layout->setVisible(false);
            weapons_layout->setVisible(false);
            pets_layout->setVisible(true);
            
            pets_layout->setZOrder(container_1_Zorder);
            clothes_layout->setZOrder(container_2_Zorder);
            weapons_layout->setZOrder(container_3_Zorder);
            
            pets_layout->setPosition(container_1_Position);
            clothes_layout->setPosition(container_2_Position);
            weapons_layout->setPosition(container_3_Position);
            
            // equip slot touch able
            pets_layout->setTouchEnabled(true);
            CCDICT_FOREACH(m_dicPetsSlot, element)
            {
                UIWidget* child = dynamic_cast<UIWidget*>(element->getObject());
                child->setTouchEnabled(true);
            }
            CCDICT_FOREACH(m_dicPets, element)
            {
                UIWidget* child = dynamic_cast<UIWidget*>(element->getObject());
                child->setTouchEnabled(true);
            }
            clothes_layout->setTouchEnabled(false);
            CCDICT_FOREACH(m_dicClothesSlot, element)
            {
                UIWidget* child = dynamic_cast<UIWidget*>(element->getObject());
                child->setTouchEnabled(false);
            }
            CCDICT_FOREACH(m_dicClothes, element)
            {
                UIWidget* child = dynamic_cast<UIWidget*>(element->getObject());
                child->setTouchEnabled(false);
            }
            weapons_layout->setTouchEnabled(false);
            CCDICT_FOREACH(m_dicWeaponsSlot, element)
            {
                UIWidget* child = dynamic_cast<UIWidget*>(element->getObject());
                child->setTouchEnabled(false);
            }
            CCDICT_FOREACH(m_dicWeapons, element)
            {
                UIWidget* child = dynamic_cast<UIWidget*>(element->getObject());
                child->setTouchEnabled(false);
            }
        }
            break;
            
        default:
            break;
    }

    
}

void CocosGUIExamplesEquipScene::touchEvent(CCObject *pSender, TouchEventType type)
{
    switch (type)
    {
        case TOUCH_EVENT_BEGAN:
            touch(pSender);
            break;
        case TOUCH_EVENT_MOVED:
            move(pSender);
            break;
        case TOUCH_EVENT_ENDED:
            drop(pSender);
            break;
    }
}


//按下
void CocosGUIExamplesEquipScene::touch(cocos2d::CCObject *pSender)
{
    UIWidget* widget = dynamic_cast<UIWidget*>(pSender);
    CCPoint worldSpace = widget->convertToWorldSpace(CCPointZero);  //坐标转换到游戏世界坐标
    
    widgetLastWorldSpace = worldSpace;
    widgetLastNodeSpace = widget->getPosition();
    
    lastWidgetParent =(UIWidget* )(widget->getParent());
    widget->removeFromParentAndCleanup(false);          //删除节点
    
    m_pUIlayer->addWidget(widget);
    
    widget->setPosition(widget->getTouchStartPos());
    movePoint = widget->getTouchStartPos();
}

//移动
void CocosGUIExamplesEquipScene::move(CCObject* pSender)
{
    UIWidget* widget = dynamic_cast<UIWidget*>(pSender);
    
    lastPoint = movePoint;
    movePoint = widget->getTouchMovePos();
    CCPoint offset = ccpSub(movePoint, lastPoint);
    CCPoint toPoint = ccpAdd(widget->getPosition(), offset);
    widget->setPosition(toPoint);
}

//放下
void CocosGUIExamplesEquipScene::drop(cocos2d::CCObject *pSender)
{
    bool isInUsedSlot = false;
    bool isInEquipSlot = false;
    
    UIWidget* widget = dynamic_cast<UIWidget*>(pSender);
    
    CCDictElement* element = NULL;
    
     // drop into used slot
     CCDICT_FOREACH(m_dicBeUsedSlot, element)
    {
        UIWidget* usedSlot_wigt = dynamic_cast<UIWidget*>(element->getObject());
        if (usedSlot_wigt->getChildren()->count() > 0)
        {
            continue;
        }
        //碰撞检测
        if (usedSlot_wigt->hitTest(widget->getPosition()))
        {
            widget->removeFromParentAndCleanup(false);
            widget->setPosition(CCPointZero);
            usedSlot_wigt->setScale(1.1);
            usedSlot_wigt->addChild(widget);
            isInUsedSlot = true;
            break;
        }
    }
    
    //判断移到哪个类型仓库(衣服、武器、宠物)
    CCDictionary* equipSlot_dic = NULL;
    CCDictionary* equip_dic = NULL;
    switch (m_eEquipType)
    {
        case EQUIP_TYPE_CLOTHES:
            equipSlot_dic = m_dicClothesSlot;
            equip_dic = m_dicClothes;
            break;
            
        case EQUIP_TYPE_WEAPONS:
            equipSlot_dic = m_dicWeaponsSlot;
            equip_dic = m_dicWeapons;
            break;
            
        case EQUIP_TYPE_PETS:
            equipSlot_dic = m_dicPetsSlot;
            equip_dic = m_dicPets;
            break;
            
        default:
            break;
    }
    
    CCDICT_FOREACH(equipSlot_dic, element)
    {
        UIWidget* equipSlot = dynamic_cast<UIWidget*>(element->getObject());
        if (equipSlot->getChildren()->count() > 0)
        {
            continue;
        }
        
        if (equipSlot->hitTest(widget->getPosition()))
        {
            CCObject* obj = equip_dic->objectForKey(widget->getName());
            if (obj)
            {
                widget->removeFromParentAndCleanup(false);
                widget->setPosition(CCPointZero);
                equipSlot->addChild(widget);
                
                isInEquipSlot = true;
            }
            break;
        }
    }

    // back to last position if cannot drop other slot
    // 若仓库已有物品,返回原来位置
    if (!isInUsedSlot && !isInEquipSlot)
    {
        CCPoint point = widgetLastWorldSpace;
        CCMoveTo* moveTo = CCMoveTo::create(1.0f, point);
        CCEaseExponentialOut* ease = CCEaseExponentialOut::create(moveTo);
        CCCallFuncO* calllFunc0 = CCCallFuncO::create(this, callfuncO_selector(CocosGUIExamplesEquipScene::backOver), widget);
        CCSequence* seq = CCSequence::create(ease, calllFunc0, NULL);
        widget->runAction(seq);
        
        // widget in equip slot
        CCDICT_FOREACH(equip_dic, element)
        {
            UIWidget* widget = dynamic_cast<UIWidget*>(element->getObject());
            widget->setTouchEnabled(false);
        }
        
        // equip up layout
        Layout* equipe_root = dynamic_cast<Layout*>(m_pUIlayer->getWidgetByTag(EQUIP_LAYOUT_TAG_ROOT));
        Layout* up_layout = dynamic_cast<Layout*>(equipe_root->getChildByName("up_panel"));
        CCObject* obj = NULL;
        up_layout->setTouchEnabled(false);
        CCARRAY_FOREACH(up_layout->getChildren(), obj)
        {
            UIWidget* child = dynamic_cast<UIWidget*>(obj);
            child->setTouchEnabled(false);
        }
    }

}

//碰撞条件不满足返回原来位置
void CocosGUIExamplesEquipScene::backOver(CCObject *pObject)
{
    UIWidget* widget = dynamic_cast<UIWidget*>(pObject);
    
    widget->removeFromParentAndCleanup(false);
    lastWidgetParent->addChild(widget);
    widget->setPosition(widgetLastNodeSpace);
    
    CCDictElement* element = NULL;
    
    // equip
    CCDictionary* equip_dic = NULL;
    switch (m_eEquipType)
    {
        case EQUIP_TYPE_CLOTHES:
            equip_dic = m_dicClothes;
            break;
            
        case EQUIP_TYPE_WEAPONS:
            equip_dic = m_dicWeapons;
            break;
            
        case EQUIP_TYPE_PETS:
            equip_dic = m_dicPets;
            break;
            
        default:
            break;
    }
    CCDICT_FOREACH(equip_dic, element)
    {
        UIWidget* widget = dynamic_cast<UIWidget*>(element->getObject());
        widget->setTouchEnabled(true);
    }
    
    // equip up layout
    Layout* equip_root = dynamic_cast<Layout*>(m_pUIlayer->getWidgetByTag(EQUIP_LAYOUT_TAG_ROOT));
    Layout* up_layout = dynamic_cast<Layout*>(equip_root->getChildByName("up_panel"));
    up_layout->setTouchEnabled(true);
    CCObject* obj = NULL;
    CCARRAY_FOREACH(up_layout->getChildren(), obj)
    {
        UIWidget* child = dynamic_cast<UIWidget*>(obj);
        child->setTouchEnabled(true);
    }
}

//退出
void CocosGUIExamplesEquipScene::menuCloseCallback(CCObject* pSender)
{
    CCDirector::sharedDirector()->end();
    
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
}

    注:大家最好看下cocos2d-x ,容器及常用API使用方法,如:CCDictionary、hitTest(碰撞检测)等。

    如上,只是实现背包的基本功能,还有好多东西,需要改进。比如,仓库不应该使用已设定好的格子,最好使用动态变化的格子,这方便以后的格子扩展。

    在此,望广大网友,多多指教~~~


示例资源及代码:  https://github.com/chukong/CocoStudioSamples 

从零开始学习cocoStudio(4)--背包功能

上一篇:WebApis中BOM的学习


下一篇:WebApis中DOM操作的基本案例