Detect how much touch is moved on UI:Widget?

I want to collect items if user touch and release. But if he swipes then it should scroll instead of collecting. Problem is on high dpi devices even if user doesn’t move a finger but the touch_moved state is called which never allow for collection of objects. Is there any built in solution? or else how can I find the amount of touch moved so I update my logic accordingly(for example in pixels etc)? Here is my current code.

		button->addTouchEventListener([=](Ref* sender, cocos2d::ui::Widget::TouchEventType type) {
				if (type == cocos2d::ui::Widget::TouchEventType::BEGAN) {
					allowCollection = true;
				} else
				if (type == cocos2d::ui::Widget::TouchEventType::MOVED) {
                    log("Challenge Moved");
					allowCollection = false;
				} else
                if (type == cocos2d::ui::Widget::TouchEventType::ENDED && allowCollection) {
                    collectItem();
                }            
}

“How much” touch is moved?
Maybe using static variables (or variables in the class) to save the first and last position of movement? Using Touch for get Location. Then you could subtract to know the difference.

Hope it helps.

well how to get first and last location? Not sure what type is *sender exactly!

For example:

bool HelloWorld::onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *event)
{

firstPosition = touch->getLocation();

}


void HelloWorld::onTouchMoved(cocos2d::Touch *touch, cocos2d::Event *event)
{

isMoved = true;

}



void HelloWorld::onTouchEnded(cocos2d::Touch *touch, cocos2d::Event *event)
{

lastPosition = touch->getLocation();

if(isMoved == true)
   difference = lastPosition - firstPosition;


isMoved = false;

}

Where firstPosition, lastPosition and difference are Point variables defined in the class, and isMoved a bool defined in the class… (it’s only an example)
If you want to get x and y, you could call touch->getLocation().x and touch->getLocation().y

Example doc:
https://docs.cocos2d-x.org/cocos2d-x/en/event_dispatcher/touch.html

1 Like

fixed by this:

if (type == ui::Widget::TouchEventType::ENDED && ((button->getTouchBeganPosition() - button->getTouchEndPosition()).length() < 50) ) {

I just wanted to know about functions to get positions.