点击事件与屏幕溢出判断

首先创建侦听事件:

<span style="white-space:pre">	</span>auto listen = EventListenerTouchOneByOne::create();
	listen->onTouchBegan = CC_CALLBACK_2(Plane1::onTouchBegan, this);
	listen->onTouchMoved = CC_CALLBACK_2(Plane1::onTouchMoved, this);
	listen->onTouchEnded = CC_CALLBACK_2(Plane1::onTouchEnded, this);
	listen->onTouchCancelled = CC_CALLBACK_2(Plane1::onTouchCancelled, this);
	listen->setSwallowTouches(true);


然后为对象写上点击事件,判断对象是否在点上,写上方法:

<span style="color: rgb(255, 0, 0); white-space: pre;">	</span>listen->onTouchBegan = [](Touch* touch, Event* event){
		auto target = static_cast<Sprite*>(event->getCurrentTarget());
		Vec2 locationInNode = target->convertToNodeSpace(touch->getLocation());       
		Size s = target->getContentSize();
		Rect rect = Rect(0, 0, s.width, s.height);
		if (rect.containsPoint(locationInNode)){
			return true;
		}
		return false;
	};


移动方法,判断点击后移动对象:

listen->onTouchMoved = [](Touch* touch, Event* event){}
		auto target = static_cast<Sprite*>(event->getCurrentTarget());      //获得对象getCurrentTarget();
		target->setPosition(target->getPosition() + touch->getDelta());    //偏移getDelta();
		Size visibleSize = Director::getInstance()->getVisibleSize();
		Point origin = Director::getInstance()->getVisibleOrigin();<pre name="code" class="cpp">}

 


移动方法里写上屏幕大小的适配,目的就是防止对象移动到场景外:

/*X轴*/
		if (target->getPositionX() + touch->getDelta().x >= visibleSize.width - target->getContentSize().width / 2){
			target->setPositionX(visibleSize.width - target->getContentSize().width / 2);
		}

		else if (target->getPositionX() + touch->getDelta().x <= target->getContentSize().width / 2){
			target->setPositionX(target->getContentSize().width / 2);
		}

		else{
			target->setPositionX(target->getPositionX() + touch->getDelta().x);
		}

		/*Y轴*/
		if (target->getPositionY() + touch->getDelta().y >= visibleSize.height - target->getContentSize().height / 2){
			target->setPositionY(visibleSize.height - target->getContentSize().height / 2);
		}

		else if (target->getPositionY() + touch->getDelta().y <= target->getContentSize().height / 2){
			target->setPositionY(target->getContentSize().height / 2);
		}

		else{
			target->setPositionY(target->getPosition().y + touch->getDelta().y);
		}<span style="color:#ff0000;">
</span>

首先target获取到点击的对象,然后判断它移动是否超出场景边界,当它超出边界时就默认它为最大边界,这样子就可以让它保持最大边界的极限值,从而达到效果。这里就是点击事件的代码,还有边界问题,有一些头文件的调用就在这里省略了,具体的方法可以去查看cocos的API,参照这里就知道它的具体使用。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值