zoukankan      html  css  js  c++  java
  • 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());
    }



    源代码下载地址:http://download.csdn.net/detail/oyangyufu/7415923


     

  • 相关阅读:
    使用 RemObjects SDK 建立 WebService 应用
    Excel文件读写的.NET开源组件 Koogra Excel BIFF/XLSX Reader Library
    DataSnap 2009 系列之三 (生命周期篇)
    更改SQL Server表所有者的操作方法
    delphi调用cmd的两种方法
    用AndroidX86和VirtualBox打造高性能Android开发环境
    DevExpress 换肤
    Remobjects关于Channel is Busy 错误的解决方法
    关于D7“System.pas not found”错误的解决方法
    40 套漂亮的图标
  • 原文地址:https://www.cnblogs.com/claireyuancy/p/6813215.html
Copyright © 2011-2022 走看看