cocos2dx 官网的小游戏 2

第四节:怎样发射一些子弹


在HelloWorld.cpp文件中的init方法中添加
this->setIsTouchEnabled(true);  //使可触摸


在HelloWorldScene.h文件中声明
void ccTouchesEnded(cocos2d::CCSet* touches, cocos2d::CCEvent* event); 

在HelloWorldScene.cpp文件中实现该方法

void HelloWorld::ccTouchesEnded(CCSet* touches, CCEvent* event){
     // Choose one of the touches to work with  获取坐标点
     CCTouch* touch = (CCTouch*)( touches->anyObject() );
     CCPoint location = touch->locationInView(touch->view());
     location = CCDirector::sharedDirector()->convertToGL(location);
 
     // Set up initial location of projectile
    CCSize winSize = CCDirector::sharedDirector()->getWinSize();
    CCSprite *projectile = CCSprite::spriteWithFile("Projectile.png",CCRectMake(0, 0, 20, 20));
    projectile->setPosition( ccp(20, winSize.height/2) );

    // Determinie offset of location to projectile
    int offX = location.x - projectile->getPosition().x;
    int offY = location.y - projectile->getPosition().y;

    // Bail out if we are shooting down or backwards
    if (offX <= 0) return;

    // Ok to add now - we've double checked position
    this->addChild(projectile);

    // Determine where we wish to shoot the projectile to
    int realX = winSize.width
                         + (projectile->getContentSize().width/2);
    float ratio = (float)offY / (float)offX;
    int realY = (realX * ratio) + projectile->getPosition().y;
    CCPoint realDest = ccp(realX, realY);
    // Determine the length of how far we're shooting
    int offRealX = realX - projectile->getPosition().x;
    int offRealY = realY - projectile->getPosition().y;
    float length = sqrtf((offRealX * offRealX) 
                                        + (offRealY*offRealY));
    float velocity = 480/1; // 480pixels/1sec
    float realMoveDuration = length/velocity;

    // Move projectile to actual endpoint
    projectile->runAction( CCSequence::actions(
        CCMoveTo::actionWithDuration(realMoveDuration, realDest),
        CCCallFuncN::actionWithTarget(this, 

        callfuncN_selector(HelloWorld::spriteMoveFinished)), 
        NULL) );
}



cocos2dx 官网的小游戏 2


第五节:检测碰撞
   我们要为两个精灵添加tag,setTag和getTag
在文件中HelloWorldScene.h添加以下两个方法  两个精灵的集合
protected:
  cocos2d::CCMutableArray<cocos2d::CCSprite*> *_targets;  
  cocos2d::CCMutableArray<cocos2d::CCSprite*> *_projectiles;


// in init()   在init方法中 实例化精灵数组
// Initialize arrays
_targets = new CCMutableArray<CCSprite*>;
 _projectiles = new CCMutableArray<CCSprite*>;    
 
 HelloWorld::~HelloWorld(){   //在析构函数中  释放内存操作
  if (_targets){
    _targets->release();
    _targets = NULL;
  }

  if (_projectiles){
    _projectiles->release();
    _projectiles = NULL;
  }

  // cpp don't need to call super dealloc
  // virtual destructor will do this
}

HelloWorld::HelloWorld():_targets(NULL),_projectiles(NULL){
	
}    


修改 addTarget() to add a new target to targets array, and set its tag to be 1.
// Add to targets array
target->setTag(1);
_targets->addObject(target);

修改ccTouchesEnded()方法  
Modify ccTouchesEnded() to add a new bullet to bullets array, and set its tag to be 2.
// Add to projectiles array
projectile->setTag(2);
_projectiles->addObject(projectile);


modify spriteMoveFinished()
void HelloWorld::spriteMoveFinished(CCNode* sender){
   CCSprite *sprite = (CCSprite *)sender;
   this->removeChild(sprite, true);
 
   if (sprite->getTag() == 1){  // target
     _targets->removeObject(sprite);
   }
  else if (sprite->getTag() == 2){  // projectile
    _projectiles->removeObject(sprite);
  }
}    


在头文件中声明void update(ccTime dt)方法
每一帧检测碰撞
void HelloWorld::update(ccTime dt){
   CCMutableArray<CCSprite*> *projectilesToDelete = new CCMutableArray<CCSprite*>;
   CCMutableArray<CCSprite*>::CCMutableArrayIterator it, jt;
 
   for (it = _projectiles->begin(); it != _projectiles->end(); it++){
    CCSprite *projectile =*it;
    CCRect projectileRect = CCRectMake(
        projectile->getPosition().x 
                          - (projectile->getContentSize().width/2),
        projectile->getPosition().y 		
                          - (projectile->getContentSize().height/2),
        projectile->getContentSize().width,
        projectile->getContentSize().height);

    CCMutableArray<CCSprite*>*targetsToDelete 
                          = new CCMutableArray<CCSprite*>;

    for (jt = _targets->begin(); jt != _targets->end(); jt++){
      CCSprite *target =*jt;
      CCRect targetRect = CCRectMake(
        target->getPosition().x - (target->getContentSize().width/2),
        target->getPosition().y - (target->getContentSize().height/2),
        target->getContentSize().width,
        target->getContentSize().height);

      if (CCRect::CCRectIntersectsRect(projectileRect, targetRect)) {
        targetsToDelete->addObject(target);
      }
    }

    for (jt = targetsToDelete->begin(); jt != targetsToDelete->end(); jt++){
      CCSprite *target =*jt;
      _targets->removeObject(target);
      this->removeChild(target, true);
    }

   if (targetsToDelete->count() >0){
      projectilesToDelete->addObject(projectile);
    }
    targetsToDelete->release();
  }

  for (it = projectilesToDelete->begin(); it != projectilesToDelete->end(); it++){
    CCSprite* projectile =*it;
    _projectiles->removeObject(projectile);
    this->removeChild(projectile, true);
  }
  projectilesToDelete->release();
}    


调用这个方法
this->schedule( schedule_selector(HelloWorld::update) ); 



第六节 怎么播放声音
HelloWorldScene.cpp中添加
#include "SimpleAudioEngine.h"

在init().方法中
CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic("background-music-aac.wav", true); 


在in ccTouchesEnded() 方法中
CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect("pew-pew-lei.wav");



第七节 :加入场景跳转

GameOverScene.h:

#ifndef _GAME_OVER_SCENE_H_
#define _GAME_OVER_SCENE_H_

#include "cocos2d.h" 
class GameOverLayer : public cocos2d::CCLayerColor{
 public:
     GameOverLayer():_label(NULL) {};
    virtual ~GameOverLayer();
    bool init();
    LAYER_NODE_FUNC(GameOverLayer);

    void gameOverDone();

    CC_SYNTHESIZE_READONLY(cocos2d::CCLabelTTF*, _label, Label);
};

class GameOverScene : public cocos2d::CCScene{
  public:
    GameOverScene():_layer(NULL) {};
    ~GameOverScene();
    bool init();
    SCENE_NODE_FUNC(GameOverScene);

    CC_SYNTHESIZE_READONLY(GameOverLayer*, _layer, Layer);
};
#endif // _GAME_OVER_SCENE_H_



GameOverScene.cpp:

#include "GameOverScene.h" 
#include "HelloWorldScene.h" 
 using namespace cocos2d; 
 bool GameOverScene::init(){
     if( CCScene::init() ){
        this->_layer = GameOverLayer::node();
        this->_layer->retain();
        this->addChild(_layer);

        return true;
    }else{
        return false;
    }
}

GameOverScene::~GameOverScene(){
    if (_layer){
        _layer->release();
        _layer = NULL;
    }
}

bool GameOverLayer::init(){
    if ( CCLayerColor::initWithColor( ccc4(255,255,255,255) ) )    {
        CCSize winSize = CCDirector::sharedDirector()->getWinSize();
        this->_label = CCLabelTTF::labelWithString("","Artial", 32);
        _label->retain();
        _label->setColor( ccc3(0, 0, 0) );
        _label->setPosition(ccp(winSize.width/2, winSize.height/2));
        this->addChild(_label);

        this->runAction( CCSequence::actions(
        CCDelayTime::actionWithDuration(3),
        CCCallFunc::actionWithTarget(this, 
            callfunc_selector(GameOverLayer::gameOverDone)),
            NULL));

        return true;
    }else{
        return false;
    }
}

void GameOverLayer::gameOverDone(){
    CCDirector::sharedDirector()->replaceScene(HelloWorld::scene());
}

GameOverLayer::~GameOverLayer(){
    if (_label){
        _label->release();
        _label = NULL;
    }
}



HelloWorldScene.h:
protected:
   int _projectilesDestroyed;    




And Initialize it in HelloWorld::HelloWorld(),

_projectilesDestroyed = 0;



After removeChild(target) in the targetsToDelete for loop of HelloWorld::update(), add the codes below to check the win condition.

_projectilesDestroyed++;                       
if (_projectilesDestroyed > 30){
  GameOverScene *gameOverScene = GameOverScene::node();
  gameOverScene->getLayer()->getLabel()->setString("You Win!");
  CCDirector::sharedDirector()->replaceScene(gameOverScene);
}


Add the codes below to check the failure condition in the “if (sprite->getTag() == 1)” conditional of spriteMoveFinished(),

GameOverScene *gameOverScene = GameOverScene::node();
gameOverScene->getLayer()->getLabel()->setString("You Lose :[");
CCDirector::sharedDirector()->replaceScene(gameOverScene);    


最好在android.mk文件中加入
LOCAL_SRC_FILES := AppDelegate.cpp \
                   HelloWorldScene.cpp \
                   GameOverScene.cpp



你可能感兴趣的:(cocos2dx)