1. 程式人生 > >Cocos2d-x 精靈碰撞檢測(方法一)

Cocos2d-x 精靈碰撞檢測(方法一)


宣告函式碰撞檢測函式,兩個精靈和重寫update

	bool isCollision( CCPoint p1,CCPoint p2,int w1,int h1,int w2,int h2 );
	CCSprite *sp2;
	CCSprite *sp1;
	virtual void update(float delta);

	//重寫觸控事件
	virtual void registerWithTouchDispatcher();
	virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent);
	virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent);
	virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent);

cpp檔案實現
初始2個精靈

	sp1 = CCSprite::create("5.png");
	sp1->setScale(0.3);
	sp1->setPosition(ccp(100, visibleSize.height/2));
	this->addChild(sp1);

	sp2 = CCSprite::create("6.png");
	sp2->setScale(0.3);
	sp2->setPosition(ccp(300, visibleSize.height/2));
	this->addChild(sp2);

開啟觸控及定時器

	setTouchEnabled(true);
	scheduleUpdate();

觸控移動精靈sp2與精靈sp1發生碰撞

bool HelloWorld::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
{
	return true;
}
void HelloWorld::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent)
{
	;
}
//移動精靈
void HelloWorld::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent)
{
	CCSize winSize = CCDirector::sharedDirector()->getVisibleSize();  
	if (sp2) {  
		CCPoint pos = pTouch->getDelta();
		CCPoint currentPos = sp2->getPosition();
		currentPos = ccpAdd(currentPos, pos);  
		currentPos = ccpClamp(currentPos, CCPointZero, ccp(winSize.width, winSize.height));//限制精靈出螢幕  
		sp2->setPosition(currentPos);//移動重設精靈座標
	} 
}
void HelloWorld::registerWithTouchDispatcher()
{
	CCDirector* pDirector = CCDirector::sharedDirector();  
	pDirector->getTouchDispatcher()->addTargetedDelegate(this, 0, true);  

}

update函式檢測碰撞,isCollision引數順序:精靈1的座標,精靈2的座標,精靈1的寬,高, 精靈2的寬,高

bool HelloWorld::isCollision( CCPoint p1,CCPoint p2,int w1,int h1,int w2,int h2 )
{
	if(abs(p1.x - p2.x) < w1 + w2 && abs(p1.y - p2.y) < h1 + h2)
	{
		return true;
	}
	return false;
}
void HelloWorld::update(float delta)
{
	if (isCollision(sp1->getPosition(),sp2->getPosition(), 45, 28.3	, 47.5, 35))
	{
		CCLOG("--------Is Collision, sp2.x: %f, sp2.y: %f", sp2->getPositionX(), sp2->getPositionY());
	}
	else
		CCLOG("++++++++ Is't Collision, sp2.x: %f, sp2.y: %f", sp2->getPositionX(), sp2->getPositionY());
}