SoFunction
Updated on 2025-03-11

Cocos2d-x touch event instance

When playing mobile games, it is essential to receive our touch messages on the screen. According to our touch events, we will implement the corresponding functions. Here we will learn how touch in cocos2d-x is implemented. Touches are divided into single-point touch and multi-point touch. Let’s first look at single-point touch, which is to receive a touch of a point. The code has been written down clearly and carefully analyze the code.

bool HelloWorld::init()
{
  bool bRet = false;
  do
  {
    CC_BREAK_IF(! CCLayer::init());

	//Touch on	this->setTouchEnabled(true);

    bRet = true;
  } while (0);

  return bRet;
}

//After turning on touch, you must register a touch event, telling the engine whether you support single touch or multi-touchvoid HelloWorld::registerWithTouchDispatcher()
{
	//addTargetedDelegate registers a single touch, the first parameter represents which object to register a touch event, the second represents priority, the number exceeds the	//Small, the higher the priority. The third parameter represents whether to swallow the message. If this node accepts the message, after processing, the node with a smaller priority than it is	//I won't accept the news	CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,0,true);
}

//ccTouchBegan is a function that must be implemented, and it is also the only function with a return value of bool among the four protocol methods.//If the return value is true, the ccTouchMoved, ccTouchEnded and ccTouchCancelled functions will be responded next.//CCTouch encapsulates some attributes about touch points, such as coordinate information, CCEvent is of no usebool HelloWorld::ccTouchBegan(CCTouch * pTouch,CCEvent * pEvent)
{
	//Get the point coordinates under opengl coordinates	CCPoint point = pTouch->getLocation();

	CCSprite * sprite = CCSprite::create("");
	this->addChild(sprite);
	sprite->setPosition(point);

	return true;
}

// A method that keeps calling when your finger moves on the screenvoid HelloWorld::ccTouchMoved(CCTouch * touch,CCEvent * pEvent)
{
	//Get the point coordinates under opengl coordinates	CCPoint point = touch->getLocation();

	CCSprite * sprite = CCSprite::create("");
	this->addChild(sprite);
	sprite->setPosition(point);
}

// Methods that will be called when the finger is liftedvoid HelloWorld::ccTouchEnded(CCTouch * pTouch,CCEvent * pEvent)
{
	this->removeAllChildrenWithCleanup(true);
}
//There is anotherccTouchCancelledfunction,Called when canceling the touch event,For example, we suddenly called when we touched the screen

Next, use the knowledge we just learned to achieve the effect of dragging and dragging the elves and moving them.

bool HelloWorld::init()
{
  bool bRet = false;
  do
  {
    CC_BREAK_IF(! CCLayer::init());

		//Implement the effect of dragging and dropping elves moving		CCSprite * sprite = CCSprite::create("");
		sprite->setPosition(ccp(240,180));
		this->addChild(sprite,0,0);

		//Touch on		this->setTouchEnabled(true);

    bRet = true;
  } while (0);

  return bRet;
}

//After turning on touch, you must register a touch event, telling the engine whether you support single touch or multi-touchvoid HelloWorld::registerWithTouchDispatcher()
{
	//addTargetedDelegate registers a single touch, the first parameter represents which object to register a touch event, the second represents priority, the number exceeds the	//Small, the higher the priority. The third parameter represents whether to swallow the message. If this node accepts the message, after processing, the node with a smaller priority than it is	//I won't accept the news	CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,0,true);
}

bool HelloWorld::ccTouchBegan(CCTouch * touch,CCEvent * pEvent)
{
	CCSprite * sprite = (CCSprite *)this->getChildByTag(0);
	//Get the coordinates of the point you clicked by your finger	CCPoint point = touch->getLocation();
	//Get the area where the elves are located, CCRect includes x, y, width, height	CCRect rect = sprite->boundingBox();

	//Judge whether the point you clicked on the elf is clicked on	if((point))
	{
		// Return true and other protocol messages will be accepted		return true;
	}

	return false;
}

void HelloWorld::ccTouchMoved(CCTouch * touch,CCEvent * pEvent)
{
	/*
	 Here you can directly set the coordinates of the elf to the coordinate position of the point where the finger is located, but this will produce a jumping effect, which is visually unfavorable.
	 Because the elves are using their own anchor to occupy the coordinate position we set, rather than the point we click on the elves and put it at the position where our fingers are located
	 */

	//The current click point of the finger and the last click point of the finger were obtained respectively.	CCPoint point = touch->getLocation();
	CCPoint pointPre = touch->getPreviousLocation();
	//ccSub subtracts two points to obtain a vector of the movement direction	CCPoint direction = ccpSub(point,pointPre);

	CCSprite * sprite = (CCSprite *)this->getChildByTag(0);
	CCPoint spritePoint = sprite->getPosition();
	//ccpAdd adds the current position point of the elves and the vector of the movement direction to obtain the position point to which the elves will move to	CCPoint spriteDirection = ccpAdd(spritePoint,direction);
	sprite->setPosition(spriteDirection);
}

Next, learn multi-touch. The difference between multi-touch and single-touch is that its priority is lower than single-touch. No matter how many numbers are passed in when registering, of course there are some other differences. Let's look at the code. The following is the effect demonstrated on Windows, where multi-touch cannot be implemented on Windows.

bool HelloWorld::init()
{
  bool bRet = false;
  do
  {
    CC_BREAK_IF(! CCLayer::init());

		//Implement the effect of dragging and dropping elves moving		CCSprite * sprite = CCSprite::create("");
		sprite->setPosition(ccp(240,180));
		this->addChild(sprite,0,0);

		//Touch on		this->setTouchEnabled(true);

    bRet = true;
  } while (0);

  return bRet;
}

void HelloWorld::registerWithTouchDispatcher()
{
	//Register multi-touch, there are only two parameters inside	CCDirector::sharedDirector()->getTouchDispatcher()->addStandardDelegate(this,0);
}

//In multi-touch, these four protocol functions have es added after touch, and each protocol function does not need to be implemented, all return values ​​are void//CCSet is a collection of CCTouchvoid HelloWorld::ccTouchesBegan(CCSet * set,CCEvent * pEvent)
{
	//CCSetIterator is an iterator	CCSetIterator iterator;
	//The following method is the method to obtain the object from CCSet	for(iterator = set->begin();iterator != set->end();iterator++)
	{
		//Crew elements into CCTouch* type		CCTouch * touch = (CCTouch *)(*iterator);
		CCPoint point = touch->getLocation();

		CCSprite * sprite = CCSprite::create("");
		sprite->setPosition(point);
		this->addChild(sprite);
	}
}

Next, use the above multi-touch message to achieve the enlargement and zooming effect of the elves. The effect of enlarging and zooming of the album pictures you see is also implemented in this way, but Windows does not support multi-points, so here is just an explanation of the principle.
View source code printing help

bool HelloWorld::init()
{
  bool bRet = false;
  do
  {
    CC_BREAK_IF(! CCLayer::init());

		//Implement the effect of dragging and dropping elves moving		CCSprite * sprite = CCSprite::create("");
		sprite->setPosition(ccp(240,180));
		this->addChild(sprite,0,0);

		//Touch on		this->setTouchEnabled(true);

    bRet = true;
  } while (0);

  return bRet;
}

void HelloWorld::registerWithTouchDispatcher()
{
	//Register multi-touch, there are only two parameters inside	CCDirector::sharedDirector()->getTouchDispatcher()->addStandardDelegate(this,0);
}

void HelloWorld::ccTouchesBegan(CCSet * set,CCEvent * pEvent)
{
	CCSetIterator iterator = set->begin();
	//Get the first touch point	CCTouch * touch0 = (CCTouch *)(*iterator);
	iterator++;
	//The program will die after execution here, because Windows only supports single-point touch and does not support multiple points, so the second point will not be obtained here.	CCTouch * touch1 = (CCTouch *)(*iterator);
	length = ccpDistance(touch0->getLocation(),touch1->getLocation());
}

void HelloWorld::ccTouchesMoved(CCSet * set,CCEvent * pEvent)
{
	CCSetIterator iterator = set->begin();
	CCTouch * touch0 = (CCTouch *)(*iterator);
	iterator++;
	CCTouch * touch1 = (CCTouch *)(*iterator);
	float length2 = ccpDistance(touch0->getLocation(),touch1->getLocation());
	float times = length2/length;
	CCSprite * sprite = (CCSprite *)this->getChildByTag(0);
	sprite->setScale(times);
}