• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
linux_ios
博客园    首页    新随笔    联系   管理    订阅  订阅

cocos2dx 圆形碰撞

bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !CCLayer::init() )
    {
        return false;
    }
    CCLayerColor* colorLayer = CCLayerColor::create(ccc4(0, 0, 255, 0),480   ,320);
    
    
    addChild(colorLayer);
    
    CCLabelTTF * pLabel = CCLabelTTF::create("~还没有碰撞·~", "", 20);
    pLabel->setPosition(ccp(250,300 ));
    pLabel->setColor(ccc3(255, 255, 0));
    CCSize size = CCDirector::sharedDirector()->getWinSize();
    
    addChild(pLabel,1,900);
    
    CCSprite * sp1 =CCSprite::create("circle1.png");
    sp1->setPosition(ccp(250,200));
    addChild(sp1,0,921);
    
    CCSprite * sp2 =CCSprite::create("circle2.png");
    sp2->setPosition(ccp(250,100));
    addChild(sp2,0,922);
    return true;
}


void HelloWorld:: onEnter()
{
    CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, false);
    CCLayer::onEnter();
}
void HelloWorld::onExit()
{
    CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
    CCLayer::onExit();
}
bool HelloWorld::ccTouchBegan(CCTouch * pTouch, CCEvent * pEvent)
{
    CCPoint touchPoint = pTouch->getLocation();
    CCSprite * sp1 = (CCSprite*)this->getChildByTag(921);
    sp1->setPosition(touchPoint);
    return true;
}
void  HelloWorld::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent)
{
    CCPoint touchPoint = pTouch->getLocation();
    CCSprite * sp1 = (CCSprite*)this->getChildByTag(921);
    CCSprite * sp2 = (CCSprite*)this->getChildByTag(922);
    
    CCLabelTTF * ttf = (CCLabelTTF*)this->getChildByTag(900);

//    ttf-> setPosition(ccp(250, 300));
    
    if (this->isCircleCollision(sp1->getPosition(), sp1->getContentSize().width*0.5, sp2->getPosition(), sp2->getContentSize().width*0.5)) {
        ttf->setString("相撞啦");
    }else
        ttf->setString("没撞");
    
    sp1->setPosition(touchPoint);
    CCLOG("%f , %f ",touchPoint.x,touchPoint.y);
    CCLOG("%f,%f,%f,%f",sp1->getPosition().x,sp1->getContentSize().width*0.5,sp2->getPosition().x,sp2->getContentSize().width*0.5);
     
}
void HelloWorld::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent)
{
    CCLOG("game over");
}

bool HelloWorld::isCircleCollision (CCPoint pos1,float radius1,CCPoint pos2 ,float radius2)
{
    if (sqrt(pow(pos1.x- pos2.x,2)+pow(pos1.y-pos2.y,2))>radius1+radius2) {
        return false;
    }
    return true;
}

 

posted @ 2013-04-13 18:05  linux_ios  阅读(871)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3