cocos2dx 菜鸟进阶篇(三) scrollView(下)

这篇继续写scroll,不过这次不是用scrollView这个控件,而是自己编写一段代码实现拖动图片。假想有一张很大的地图,然后屏幕只能显示它的一角,这时候就要通过拖动来查看其他部分。本来是要用scrollView实现这个功能,可用起来始终那么别扭,这不,上午一气之下自己搞了个可以拖动图片的代码。


一、首先在init中添加自己要实现拖动到图片。

bool HelloWorld::init()
{
    bool bRet = false;
    do 
    {
        CC_BREAK_IF(! CCLayer::init());
		
		CCSize size = CCDirector::sharedDirector()->getWinSize();

		//选择的图片一定要比screan 大,要不然就会出问题。不过话说回来,你的图片如果比屏幕小,你还拖动干嘛?找茬?
		sprite = CCSprite::create("map_bg.png");
		this->addChild(sprite);
		sprite->setPosition(ccp(size.width/2,size.height/2));
		sprite->setAnchorPoint(ccp(0.5,0.5));

		//开启触摸
		setTouchEnabled(true);

        bRet = true;
    } while (0);

    return bRet;
}

二、真正实现拖动图片的代码:

void HelloWorld::ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent)
{
    CCSetIterator it = pTouches->begin();
    CCTouch* touch = (CCTouch*)(*it);

	//获取触摸开始的坐标
    m_tBeginPos = touch->getLocation();    
}

void HelloWorld::ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent)
{
    CCSetIterator it = pTouches->begin();
    CCTouch* touch = (CCTouch*)(*it);

	CCSize size = CCDirector::sharedDirector()->getWinSize();

    CCPoint touchLocation = touch->getLocation();
    float nMoveY = touchLocation.y - m_tBeginPos.y;
	float nMoveX = touchLocation.x - m_tBeginPos.x;

	//sprite 的当前坐标
    CCPoint curPos  = sprite->getPosition();
	//下一个坐标就是sprite当前坐标+鼠标移动到距离
	CCPoint nextPos = ccp(curPos.x + nMoveX, curPos.y + nMoveY);

	//最大移动距离!
	float maxMoveY = sprite->getContentSize().height/2 - size.height/2;
	float maxMoveX = sprite->getContentSize().width/2 - size.width/2;

	sprite->setPosition(nextPos);
    m_tBeginPos = touchLocation;

	//判断图片是否超出边界,切记,这下面两句一定要放在上面两句之后
	HelloWorld::judgeHV(nextPos,maxMoveY);
	HelloWorld::judgeLR(nextPos,maxMoveX);  
}

三、judgeHV跟judgeLR是为了防止图片被拖动出边界,出现黑边。

void HelloWorld::judgeHV(CCPoint nextPos,float max)
{
	CCSize size = CCDirector::sharedDirector()->getWinSize();

	//因为在if里面return是不会影响外部的,只是函数停止执行而已,函数停止了,外面的代码照常运行~
	if (nextPos.y <(size.height/2-max))
    {
		//当移动到最顶端,Y坐标为maxMoveY,不让它动
		sprite->setPositionY(size.height/2-max);
        return;
    }

	if(nextPos.y > (size.height/2 + max))
	{
		sprite->setPositionY(size.height/2 + max);
		return;
	}
}

void HelloWorld::judgeLR(CCPoint nextPos,float max)
{
	CCSize size = CCDirector::sharedDirector()->getWinSize();

	if(nextPos.x < (size.width/2 - max))
	{
		sprite->setPositionX(size.width/2 - max);
		return;
	}

	if(nextPos.x > (size.width/2 + max))
	{
		sprite->setPositionX(size.width/2 + max);
		return;
	}	
}

恩,这样就成功了。简单吧。

原文地址:https://www.cnblogs.com/start530/p/3834365.html