关于Cocos2d-x中监听物体不超越边界的解决方案

写一个监听器

touchlistener->onTouchMoved = [this](Touch* pTouch, Event*) {

  auto delta = pTouch->getDelta();

  auto hero = (PlaneHero*)getChildByTag(HERO_TAG);

  auto oldpos = hero->getPosition(); //用来重置出界后的位置

  hero->setPosition(Vec2(hero->getPosition().x + delta.x, hero->getPosition().y + delta.y));


  //不能出界
  auto winSize = Director::getInstance()->getWinSize();
  if (hero->getPositionY() < hero->getContentSize().height / 2 || hero->getPositionY() > winSize.height - hero->getContentSize().height / 2
    || hero->getPositionX() < hero->getContentSize().width / 2 || hero->getPositionX() > winSize.width - hero->getContentSize().width / 2)
  {
    hero->setPosition(oldpos);
  }
};
_eventDispatcher->addEventListenerWithSceneGraphPriority(touchlistener, this);  //把监听器添加到事件分发器

posted @ 2016-08-11 23:08  杭者  阅读(387)  评论(0编辑  收藏  举报