cocos2dx 精灵的碰撞检测和消灭(3)

原创 2013年12月02日 15:45:03

在上一篇的基础上增加了一点内容,必要的注释都写在代码里了,,就直接贴代码吧,我也懒得写详细的过程。

HelloWorldSence.h

#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__

#include "cocos2d.h"
using namespace cocos2d;

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();
    
    // a selector callback
    void menuCloseCallback(CCObject* pSender);

    // preprocessor macro for "static create()" constructor ( node() deprecated )
    CREATE_FUNC(HelloWorld);
    
    void addTarget();
    void spriteMoveFinished(CCNode *sender);
    void gameLogic(cocos2d::CCTime dt);
    
    void ccTouchesEnded(CCSet *touches, CCEvent *event);
    
    CCArray *aarayTarget;//敌人
    CCArray *arrayProjectile;//飞镖
    void update(CCTime dt);
};

#endif // __HELLOWORLD_SCENE_H__

HelloWorldScence.cpp

#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"

using namespace cocos2d;
using namespace CocosDenshion;

CCScene* HelloWorld::scene()
{
    // 'scene' is an autorelease object
    CCScene *scene = CCScene::create();
    
    // 'layer' is an autorelease object
    HelloWorld *layer = HelloWorld::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}



// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( CCLayerColor::initWithColor(ccc4(255, 255, 255, 255)) )
    {
        
        CCSize winSize = CCDirector::sharedDirector()->getWinSize();//获取屏幕大小
        
        arrayProjectile = CCArray::create();
        aarayTarget = CCArray::create();
        
        float sprite_scale = 2.0;
        CCSprite *Player =  CCSprite::create("Player.png");
        Player->setScale(sprite_scale);
        Player->setPosition(ccp(Player->getContentSize().width*sprite_scale/2.0, winSize.height/2.0));
        this->addChild(Player);
        
        aarayTarget->retain();
        arrayProjectile->retain();
        
        this->schedule(schedule_selector(HelloWorld::gameLogic), 1.0);
        this->schedule(schedule_selector(HelloWorld::update));
        this->setTouchEnabled(true);
        
        return true;
    }
    else{
        return false;
    }

    
}

void HelloWorld::gameLogic(cocos2d::CCTime dt){
    this->addTarget();
}



void HelloWorld::addTarget(){
    
    CCSize winSize = CCDirector::sharedDirector()->getWinSize();
    
    CCSprite *target = CCSprite::create("Target.png");
    
    //随机位置
    int minY = target->getContentSize().height/2.0;
    int maxY = winSize.height - target->getContentSize().height/2.0;
    int rangeY = maxY - minY;
    int actualY = rand()%rangeY + minY;
    
    target->setPosition(ccp(winSize.width - target->getContentSize().width/2.0, actualY));
    target->setTag(1);
    this->addChild(target);
    aarayTarget->addObject(target);
    
    //随机速度
    float minDuration = 2.0;
    float maxDuration = 4.0;
    int rangeDuration = maxDuration - minDuration;
    float actualDuration = rand()%rangeDuration + minDuration;
    
    
    
    
    CCFiniteTimeAction *actionMove = CCMoveTo::create(actualDuration, ccp(0 - target->getContentSize().width/2.0, actualY));//0代表屏幕外,这句表示在3秒内从初始位置移动到屏幕外
    
    
    //增加一个回调函数,回收移动到屏幕外的精灵
    CCFiniteTimeAction *actionMoveDone = CCCallFuncN::create(this, callfuncN_selector(HelloWorld::spriteMoveFinished));
    target->runAction(CCSequence::create(actionMove,actionMoveDone,NULL));
    
}

void HelloWorld::spriteMoveFinished(cocos2d::CCNode *sender){
    CCSprite *sprite = (CCSprite *)sender;
   // this->removeChild(sprite, true);
    if (sprite->getTag() == 1) {
        aarayTarget->removeObject(sprite);//清除敌人
    }else if(sprite->getTag() == 2){
        arrayProjectile->removeObject(sprite);//清除飞镖
    }
}


//发射飞镖
void HelloWorld::ccTouchesEnded(cocos2d::CCSet *touches, cocos2d::CCEvent *event){
    CCTouch *touch = (CCTouch *)touches->anyObject();
    CCPoint location = touch->getLocationInView();
    location = this->convertTouchToNodeSpace(touch);
    
    CCSize winSize = CCDirector::sharedDirector()->getWinSize();
    
    CCSprite *projectile = CCSprite::create("Projectile.png");
    projectile->setPosition(ccp(20, winSize.height/2));
    
    float offX = location.x - projectile->getPositionX();
    float offY = location.y - projectile->getPositionY();
    
    if (offX <= 0) {
        return;
    }
    projectile->setTag(2);
    this->addChild(projectile);
    arrayProjectile->addObject(projectile);
    
    float angle = offY/offX;
    float realX= winSize.width + projectile->getContentSize().width/2;
    float realY = realX * angle + projectile->getPositionY();
    
    CCPoint finalPosition = ccp(realX, realY);
    
    //获取飞镖飞行时间
    float length = sqrtf(realX *realX + realY*realY);
    float velocity = 480;
    float realMoveDuration = length/velocity;
    
    projectile->runAction(CCSequence::create(CCMoveTo::create(realMoveDuration, finalPosition),CCCallFuncN::create(this, callfuncN_selector(HelloWorld::spriteMoveFinished)),NULL));
}

//碰撞检测,消除飞镖和敌人
void HelloWorld::update(cocos2d::CCTime dt){
    for (int i = 0; i < aarayTarget->count(); i++) {
        CCSprite *target = (CCSprite *)aarayTarget->objectAtIndex(i);
        for (int j = 0; j < arrayProjectile->count(); j++) {
            CCSprite *projectile = (CCSprite *)arrayProjectile->objectAtIndex(j);
            if (target->boundingBox().intersectsRect(projectile->boundingBox())) {
                aarayTarget->removeObjectAtIndex(i);
                arrayProjectile->removeObjectAtIndex(j);
                this->removeChild(target);
                this->removeChild(projectile);
                
                break;
            }
        }
    }
}



void HelloWorld::menuCloseCallback(CCObject* pSender)
{
    CCDirector::sharedDirector()->end();

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
}

运行结果截图:


cocos2dx3.x物理引擎的碰撞检测

这两天看了下,所以当个笔记,转载自:点击打开链接  通常在游戏简单逻辑判断和模拟真实的物理世界时,我们只需要在定时器中判断游戏中各个精灵的条件是否满足判断条件就可以了。例如,...

Cocos2dx物理引擎碰撞检测总结

 通常在游戏简单逻辑判断和模拟真实的物理世界时,我们只需要在定时器中判断游戏中各个精灵的条件是否满足判断条件就可以了。例如,在飞机大战中,判断我方子弹和敌机是否发生碰撞一般在定时器中通过敌机所在...

像素完美碰撞检测(使用cocos2d-x)

Pixel Perfect Collision Detection (Using Cocos2d-x) ...

使用cocos2d-x3.0和物理引擎实现碰撞检测

前言 从SpriteBatchNode中添加我们的精灵 首先,创建一个空白的项目,将实例代码删除。 接下来,让我们把资源文件放入的Resources目录下。 然后,在H...

cocos2dx 碰撞检测 总结

之前所用到的碰撞检测均为cocos提供的方法。 1、点与矩形碰撞 auto rec = tubeOn1->getBoundingbox();// 得要矩形区域 bool collision = ...

实例介绍Cocos2d-x物理引擎:碰撞检测

碰撞检测是使用物理引擎的一个重要目的,使用物理引擎可以进行精确的碰撞检测,而且执行的效率也很高。在Cocos2d-x 3.x中使用事件派发机制管理碰撞事件,EventListenerPhysicsCo...

Delphi7高级应用开发随书源码

  • 2003年04月30日 00:00
  • 676KB
  • 下载

Cocos2d-x3.2总结(四)使用物理引擎进行碰撞检测

如果你在游戏中
  • cbbbc
  • cbbbc
  • 2014年08月13日 19:10
  • 5181

cocos-Lua 捕鱼碰撞检测方法

--在Lua中不用物理引擎的检测碰撞会很卡,Lua的for循环的效率比C++的低几十倍 --先绑定一个碰撞检测的事件,然后创建每个鱼的PhysicsBody,还有就是设置物理掩码,都设置为无碰撞效果,...

cocos2dx3.2 物理引擎之碰撞

#include "HelloWorldScene.h" USING_NS_CC; //物理引擎标识 int ball1Mask = 1
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:cocos2dx 精灵的碰撞检测和消灭(3)
举报原因:
原因补充:

(最多只允许输入30个字)