首页 > 代码库 > cocos3.0通过精灵控制精灵的触摸事件的实现
cocos3.0通过精灵控制精灵的触摸事件的实现
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); }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。