cocos2d 主角更随触屏走

bool HelloWorld::init()
{
    if ( !CCLayer::init() )
    {
        return false;
    }
    
    CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
    CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();
    hero= CCSprite::create("1.png");
    hero->setPosition(ccp(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));
    this->addChild(hero, 0);

    CCDirector* pDirector=CCDirector::sharedDirector();
    pDirector->getTouchDispatcher()->addTargetedDelegate(this,0,true);

    return true;
}

bool HelloWorld::ccTouchBegan(CCTouch* touch,CCEvent* event)
{
    CCPoint heropos=hero->getPosition();
    CCPoint location=touch->getLocationInView();
    location=CCDirector::sharedDirector()->convertToGL(location);
    if(location.x>heropos.x-32&&location.x<heropos.x+32&&
        location.y>heropos.y-32&&location.y<heropos.y+32)
    {
        isControl=true;
        deltax=location.x-heropos.x;
        deltay=location.y-heropos.y;
    }
    return true;
}

void HelloWorld::ccTouchMoved(CCTouch* touch,CCEvent* event)
{
    if(isControl)
    {
        CCPoint location=touch->getLocationInView();
        location=CCDirector::sharedDirector()->convertToGL(location);
        float x=location.x-deltax;
        float y=location.y-deltay;
        hero->setPosition(ccp(x,y));
    }
}
原文地址:https://www.cnblogs.com/yufenghou/p/3959434.html