CCBlockTouchLayer.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. //
  2. // CCBlockTouchLayer.cpp
  3. // cocos2d_libs
  4. //
  5. // Created by zhuge on 2023/3/16.
  6. //
  7. #include "CCBlockTouchLayer.h"
  8. #include "base/CCDirector.h"
  9. #include "base/CCEventDispatcher.h"
  10. #include "base/CCEventListenerTouch.h"
  11. cocos2d::CCBlockTouchLayer::CCBlockTouchLayer() {
  12. }
  13. cocos2d::CCBlockTouchLayer::~CCBlockTouchLayer() {
  14. }
  15. bool cocos2d::CCBlockTouchLayer::init() {
  16. if (!cocos2d::Layer::init()) {
  17. return false;
  18. }
  19. _registTouch();
  20. return true;
  21. }
  22. void cocos2d::CCBlockTouchLayer::_registTouch() {
  23. auto listener = cocos2d::EventListenerTouchOneByOne::create();
  24. listener->setSwallowTouches(true);
  25. listener->onTouchBegan = [this](cocos2d::Touch*, cocos2d::Event*) -> bool {
  26. if (this->isVisible() && this->hasVisibleParents()) {
  27. // block all touches if visible
  28. return true;
  29. } else {
  30. return false;
  31. }
  32. };
  33. cocos2d::Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);
  34. }
  35. bool cocos2d::CCBlockTouchLayer::hasVisibleParents(){
  36. auto parent = this->getParent();
  37. for( auto c = parent; c != nullptr; c = c->getParent() )
  38. {
  39. if( !c->isVisible() )
  40. {
  41. return false;
  42. }
  43. }
  44. return true;
  45. }