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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Box2D和Cocos2D是两个游戏开发框架。Box2D是一个用于物理模拟的开源库,可以模拟刚体的运动和碰撞等物理效果。Cocos2D是一个用于2D游戏开发的跨平台框架,提供了丰富的图形渲染和用户交互功能。\[1\] 在使用Cocos2D和Box2D进行游戏开发时,你可以利用Box2D来处理游戏中的物理效果,比如重力、碰撞和刚体运动等。Cocos2D提供了与Box2D的集成,使得开发者可以方便地在Cocos2D中使用Box2D的功能。你可以通过创建物理世界、添加刚体和设置碰撞检测等来实现游戏中的物理效果。\[2\] 如果你刚刚接触Cocos2D和Box2D,建议你先学习Cocos2D和Box2D的基础知识,然后再深入学习如何在Cocos2D中使用Box2D。你可以参考一些入门教程,比如《Cocos2D入门》和《Box2D入门》。如果你对OpenGL ES 2.0和自定义Cocos2D 2.X着色器等背景知识感到困惑,你可以查阅相关教程来获取更多的帮助。\[3\] #### 引用[.reference_title] - *1* *3* [如何使用Box2D和Cocos2D制作一款像Fruit Ninja一样的游戏-第1部分](https://blog.csdn.net/kaka626/article/details/9397825)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [用Box2D和cocos2d-x制作弹弓类游戏](https://blog.csdn.net/qq55008307/article/details/8090839)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值