天天看點

cocos2dx 碰撞

#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__

#include "cocos2d.h"
#include "SimpleAudioEngine.h"
USING_NS_CC;
using namespace CocosDenshion;  
class HelloWorld : public cocos2d::CCLayerColor
{
public:
	
    // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
    virtual bool init();  

	void addTarget();

	void spriteMoveFinished(CCNode* sender);

	void gameLogic(float dt);

	void update(float dt);
	virtual void ccTouchesEnded(cocos2d::CCSet* touches, cocos2d::CCEvent* event);
    // there's no 'id' in cpp, so we recommand to return the exactly class pointer
    static cocos2d::CCScene* scene();
    
    // a selector callback
    void menuCloseCallback(CCObject* pSender);
	
	int _projectilesDestroyed;

	cocos2d::CCArray *_targets;
	cocos2d::CCArray *_projectiles;

    // implement the "static node()" method manually
    CREATE_FUNC(HelloWorld);


};

#endif  // __HELLOWORLD_SCENE_H__
           

cpp檔案:

#include "HelloWorldScene.h"


CCScene* HelloWorld::scene()
{
    CCScene * scene = NULL;
    scene = CCScene::create();
    CCLayer *layer = HelloWorld::create();
    scene->addChild(layer);
    return scene;
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
	CCLayer::init();
	_targets =   CCArray::create();
	_targets->retain();
	_projectiles = CCArray::create();
	_projectiles->retain();

	_projectilesDestroyed = 0;

	CCSize size = CCDirector::sharedDirector()->getWinSize();
	CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
	CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();
	CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
			"CloseNormal.png",
			"CloseSelected.png",
			this,
			menu_selector(HelloWorld::menuCloseCallback));

	pCloseItem->setPosition(ccp(origin.x + visibleSize.width - pCloseItem->getContentSize().width/2 ,
			origin.y + pCloseItem->getContentSize().height/2));

		
	CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
	pMenu->setPosition(CCPointZero);
	this->addChild(pMenu, 1);
		
	CCSprite *pSprite = CCSprite::create("Player.png",CCRectMake(0,0,27,40));
	pSprite->setPosition(ccp(pSprite->getContentSize().width/2,size.height/2));
	this->addChild(pSprite);


	//schedule_selector 監聽;;
	this->schedule( schedule_selector(HelloWorld::gameLogic), 1.0 );



	//每次繪制判斷碰撞;
	this->schedule( schedule_selector(HelloWorld::update) );
		
	//添加背景音樂;
	CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic(
						"background-music-aac.wav", true);  

	this->initWithColor(ccc4(255,255,255,255));
		
	this->setTouchEnabled(true);
  
 

    return true;
}


void HelloWorld::addTarget()
{
	//首先初始化精靈;
	CCSprite *pTarget = CCSprite::create("Target.png",CCRectMake(0,0,27,40));
	
	CCSize winSize = CCDirector::sharedDirector()->getWinSize();

	//計算可繪制的範圍;
	int minY = pTarget->getContentSize().height/2;
	int maxY = winSize.height - minY;
	//計算可随機基數;
	int rangeY = maxY - minY;
	//随機出的基數*半個身位 = 最後的坐标點;
	int actualY = (rand() % rangeY) + minY;

	pTarget->setPosition(ccp(winSize.width + pTarget->getContentSize().width/2 ,actualY));

	this->addChild(pTarget);
	pTarget->setTag(1);
	_targets->addObject(pTarget);

	//計算移動速度 最慢4秒移動橫屏 最快2秒;
	int minDuration = (int) 2.0;
	int maxDuration = (int) 4.0;
	int rangeDuration = maxDuration - minDuration;
	int actualDuration = (rand() % rangeDuration) +minDuration;
	
	//初始化耗時動作;
	CCFiniteTimeAction* actionMove =
		CCMoveTo::create((float)actualDuration,
		ccp(0 - pTarget->getContentSize().width/2,actualY));
	CCFiniteTimeAction* actionMoveDone =
		CCCallFuncN::create(this,
		callfuncN_selector(HelloWorld::spriteMoveFinished));

	//綁定動作;
	pTarget->runAction(CCSequence::create(actionMove,actionMoveDone,NULL));
}

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 HelloWorld::gameLogic(float dt)
{
	this->addTarget();
}

void HelloWorld::ccTouchesEnded(CCSet* touches, CCEvent* event)
{
	CCTouch *touch = (CCTouch *) touches->anyObject();
	CCPoint location = touch->getLocationInView();

	location = CCDirector::sharedDirector()->convertToGL(location);

	CCSize size = CCDirector::sharedDirector()->getWinSize();

	CCSprite *pProjectile = CCSprite::create("Projectile.png",
		CCRectMake(0,0,20,20));

	pProjectile->setPosition(ccp(20,size.height/2));

	int offX = location.x - pProjectile->getPosition().x;
	int offY = location.y - pProjectile->getPosition().y;

	if(offX <= 0) return;
	//添加發子彈聲音;
	CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(
							"pew-pew-lei.wav"); 

	this->addChild(pProjectile);

	pProjectile->setTag(2);
	_projectiles->addObject(pProjectile);

	int realX = size.width +
		(pProjectile->getContentSize().width/2);
	float ratio = (float)offY / (float)offX;
	int realY = (realX * ratio) + pProjectile->getPosition().y;
	CCPoint realDest = ccp(realX,realY);

	int offRealX = realX - pProjectile->getPosition().x;
	int offRealY = realY - pProjectile->getPosition().y;
	float length = sqrtf((offRealX * offRealX) + (offRealY*offRealY));
	
	float velocity = 480/1;
	float realMoveDuration = length/velocity;

	pProjectile->runAction(CCSequence::create(
		CCMoveTo::create(realMoveDuration,realDest)
		,CCCallFuncN::create(this,callfuncN_selector(HelloWorld::spriteMoveFinished))
		,NULL));
}
void HelloWorld::update(float dt)
{
	CCArray *projectilesToDelete = new CCArray;
	CCArray* targetsToDelete =new CCArray;
	CCObject* it = NULL;
	CCObject* jt = NULL;

	CCARRAY_FOREACH(_projectiles, it)
	{
		CCSprite *projectile = dynamic_cast<CCSprite*>(it);
		//boundingBox()可以得到精靈的範圍;
		CCRect  projectileRect = projectile->boundingBox();
		CCARRAY_FOREACH(_targets, jt)
		{
			CCSprite *target = dynamic_cast<CCSprite*>(jt);
			CCRect targetRect = target->boundingBox();

			if (projectileRect.intersectsRect(targetRect))
			{
				targetsToDelete->addObject(target);
				projectilesToDelete->addObject(projectile);
			}
		}
	}

	CCARRAY_FOREACH(targetsToDelete, jt)
	{
		CCSprite *target = dynamic_cast<CCSprite*>(jt);
		_targets->removeObject(target);
		this->removeChild(target, true);
	}

	CCARRAY_FOREACH(projectilesToDelete, it)
	{
		CCSprite* projectile = dynamic_cast<CCSprite*>(it);
		_projectiles->removeObject(projectile);
		this->removeChild(projectile, true);  
	}

	projectilesToDelete->release();
	targetsToDelete->release();
}

void HelloWorld::menuCloseCallback(CCObject* pSender)
{
	SimpleAudioEngine::sharedEngine()->end(); //要自己手動關閉聲音引擎,不然下次編譯過不了;
    CCDirector::sharedDirector()->end();
}
           

  參考 無腦碼農的視訊啊!!

在他的代碼上改了一點點,就成自己的咯!

自己的第一篇部落格 就這樣吧 我看看怎麼樣

歡迎交流  本人QQ  :  164453625

繼續閱讀