Hi,推荐文件给你 "碰撞检测例子 2.zip" http://vdisk.weibo.com/s/J78kk
创建新工程之后,新建一个类HudLayer
HudLayer.h
#include "cocos2d.h"
USING_NS_CC;
class HudLayer:public CCLayer
{
public:
CREATE_FUNC(HudLayer);
bool init();
//调用的方法
void start();
};
HudLayer.cpp
bool HudLayer::init()
{
bool pRet = false;
do {
CC_BREAK_IF(!CCLayer::init());
//设置一个按钮
CCMenuItemImage* start = CCMenuItemImage::create("Icon-72.png", "Icon-72.png", this, menu_selector(HudLayer::start));
start->setPosition(ccp(100, 100));
CCMenu* pMenu = CCMenu::create(start,NULL);
this->addChild(pMenu);
pRet = true;
} while (0);
return pRet;
}
void HudLayer::start()
{
//发送一条消息调用相应的方法
CCNotificationCenter::sharedNotificationCenter()->postNotification("change");
}
HelloWorldScene.h
#include "HudLayer.h"
USING_NS_CC;
class HelloWorld : public cocos2d::CCLayerColor
{
public:
// Method 'init' in cocos2d-x returns bool, instead of 'id' in cocos2d-iphone (an object pointer)
virtual bool init();
// there's no 'id' in cpp, so we recommend to return the class instance pointer
static cocos2d::CCScene* scene();
HelloWorld();
//存放精灵的数组
CCArray* _arr;
//存放子弹的数组
CCArray* _mon;
void update(float dt);
HudLayer* hud;
void change();
// preprocessor macro for "static create()" constructor ( node() deprecated )
CREATE_FUNC(HelloWorld);
};
HelloWorldScene.cpp
bool HelloWorld::init()
{
//
// 1. super init first
if ( !CCLayerColor::initWithColor(ccc4(255, 255, 255, 255)))
{
return false;
}
//注册一条消息,在HudLayer类中发送的消息
CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(HelloWorld::change), "change", NULL);
CCSpriteFrameCache* cache = CCSpriteFrameCache::sharedSpriteFrameCache();
cache->addSpriteFramesWithFile("zzzz.plist");
CCSpriteBatchNode* node = CCSpriteBatchNode::create("zzzz.pvr.ccz");
this->addChild(node);
_arr = CCArray::create();
_arr->retain();
CCSprite* player = CCSprite::createWithSpriteFrameName("Player.png");
player->setPosition(ccp(100, 100));
node->addChild(player);
_arr->addObject(player);
hud = HudLayer::create();
this->addChild(hud);
//初始一个子弹池
_mon = CCArray::create();
_mon->retain();
for (int i = 0; i <10;i++ )
{
CCSprite* monster = CCSprite::createWithSpriteFrameName("projectile2.png");
node->addChild(monster);
_mon->addObject(monster);
monster->setPosition(ccp(100, 200));
}
this->scheduleUpdate();
return true;
}
void HelloWorld::update(float dt)
{
CCObject* obj1 = NULL;
CCObject* obj2 = NULL;
CCARRAY_FOREACH(_arr, obj1)
{
CCSprite* player = (CCSprite*)obj1;
CCArray* monsDelete = CCArray::create();
CCARRAY_FOREACH(_mon, obj2)
{
CCSprite* mon = (CCSprite*)obj2;
if (player->boundingBox().intersectsRect(mon->boundingBox()))
{
monsDelete->addObject(mon);
}
}
CCARRAY_FOREACH(monsDelete, obj2)
{
CCSprite* mon = (CCSprite*)obj2;
mon->setVisible(false);
}
}
}
void HelloWorld::change()
{
CCSprite* player1 = (CCSprite*)_arr->objectAtIndex(0);
CCMoveBy* moBy = CCMoveBy::create(1, ccp(0, 100));
player1->runAction(moBy);
}