I have written code for a game in which some birds are flying. I created array of CCSprite
and added them on Scene. Now it assign a scheduler to each bird object for moving in random direction in screen. All are working. Now i am getting trouble in getting collision in birds.
i am trying to run a CCARRAY_FOREACH
loop on array but its giving error.
0xC0000005: Access violation reading location 0xfeeefeee.
Please help me how i can get get collision detection in array element while they are moving. updateCollison
method is not executing.
My Code is:
#include "HelloWorldScene.h"
using namespace cocos2d;
CCScene* HelloWorld::scene()
{
CCScene * scene = NULL;
do
{
// 'scene' is an autorelease object
scene = CCScene::create();
CC_BREAK_IF(! scene);
// 'layer' is an autorelease object
HelloWorld *layer = HelloWorld::create();
CC_BREAK_IF(! layer);
// add layer as a child to scene
scene->addChild(layer);
} while (0);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
//srand(time(NULL));
CCSize size = CCDirector::sharedDirector()->getWinSize();
birds = CCArray::create();
for(int j = 0; j<5; j++){
CCSprite *bird = CCSprite::create("twitter_square.png");
bird->setTag(j);
int max = rand() % 480;
int min = rand() % 320;
bird->setPosition(ccp(max, min));
this->addChild(bird);
birds->addObject(bird);
bird->schedule( schedule_selector(HelloWorld::moveBird), 5.0 );
bird->schedule( schedule_selector(HelloWorld::updateCollison), 5.0 );
}
return true;
}
void HelloWorld::menuCloseCallback(CCObject* pSender)
{
CCDirector::sharedDirector()->end();
}
void HelloWorld::moveBird(float dt)
{
CCSize size = CCDirector::sharedDirector()->getWinSize();
int max = rand() % (int)size.width;
int min = rand() % (int)size.height;
CCActionInterval* actionTo = CCMoveTo::actionWithDuration(5, ccp(max,min));
this->runAction(actionTo);
}
void HelloWorld::updateCollison(float dt)
{
CCObject *obj;
for(int i=0; i < birds->count(); i++)
{
CCLOG("$$$$$$$$$$$$$$$$$$$$$$$");
}
}
It's better to do things in one update function ...for example make one update in that call MoveBird Function which will contain your moving bird code
Secondly now call check Collision function
void update (float dt) {
MoveBird(); // Move how many birds you want to move
CheckCollision();
}
Now how to check collision of your birds
In your collision function forLoop your birds Array check
if(mBirdsArray[i]->boundingBox().containsPoint(mBirdsArray[j]->getPosition()))
and vice versa ...
I hope this will work .. .there maybe better logic than this ..