cocos3.0通过精灵控制精灵的触摸事件的实现

本文介绍了一个使用Cocos2d-x游戏引擎实现触摸事件处理的例子,包括触摸开始(onTouchBegan)、触摸移动(onTouchMoved)及触摸结束(onTouchEnded)三个阶段的处理逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

auto listener = EventListenerTouchOneByOne::create();
	listener->setSwallowTouches(true);
	auto  sprite = this->getChildByTag(virTag)->getChildByTag(jumpTag);
	
	listener->onTouchBegan = CC_CALLBACK_2(MLayer::onTouchBegan, this);
	listener->onTouchMoved = CC_CALLBACK_2(MLayer::onTouchMoved, this);
	listener->onTouchEnded = CC_CALLBACK_2(MLayer::onTouchEnded, this);
	_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, sprite);  //该精灵享有触摸

	return  true;

}

bool  MLayer::onTouchBegan(Touch* touch, Event*  event)
{
	auto target = static_cast<Sprite*>(event->getCurrentTarget());//获取当前的触摸目标(那个跳跃精灵)
	Point locationInNode = target->convertToNodeSpace(touch->getLocation());//将本地坐标系转化为精灵坐标系(以精灵的左下角作为坐标原点)
	Size s= target->getContentSize();//获取精灵的文本尺寸大小
	Rect rect = Rect(0, 0, s.width, s.height);//获取精灵的矩形框(起始点为精灵的左下角)
	if (rect.containsPoint(locationInNode))//判断触摸点是否在精灵的矩形框上
	{
		auto sprite2 =this->getChildByTag(cmsTag)->getChildByTag(catTag);
		sprite2->setScale(0.2f);
	}
	
	return true;
}
void MLayer::onTouchMoved(Touch* touch, Event* event)
{
	auto target = static_cast<Sprite*>(event->getCurrentTarget());//获取当前的触摸目标
	Point locationInNode = target->convertToNodeSpace(touch->getLocation());//将本地坐标系转化为精灵坐标系(以精灵的左下角作为坐标原点)
	Size s = target->getContentSize();//获取精灵的文本尺寸大小
	Rect rect = Rect(0, 0, s.width, s.height);//获取精灵的矩形框(起始点为精灵的左下角)
	if (rect.containsPoint(locationInNode))//判断触摸点是否在精灵的矩形框上
	{
		target->setPosition(target->getPosition() + touch->getDelta());//将捕获的精灵坐标设在移动结束的地方
	}
}
void MLayer::onTouchEnded(Touch* touch ,Event* event)
{
	auto sprite2 = this->getChildByTag(cmsTag)->getChildByTag(catTag);
	sprite2->setScale(0.6f);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值