Cocos2d-x中,如何通过触摸来移动一个精灵

Cocos2d-x中,如何通过按住一个精灵移动手指,使精灵跟随手指移动,方法如下:

首先添加精灵,定义触摸事件

bool HelloWorld::init()
{
	if ( !Layer::init() )
	{
		return false;
	}

	ball = Sprite::create("Ball.png");
	
	auto listener = EventListenerTouchOneByOne::create();
	listener->onTouchMoved = CC_CALLBACK_2(HelloWorld::onTouchMoved, this);
	listener->onTouchBegan = CC_CALLBACK_2(HelloWorld::onTouchBegin, this);
	listener->onTouchEnded = CC_CALLBACK_2(HelloWorld::onTouchEnd, this);
	_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);

	addChild(ball);
	
	return true;
}
然后创建onTouchMoved函数

void HelloWorld::onTouchMoved(Touch* touch, Event* event){
	Rect ballRect = ball->getBoundingBox();
	//获取精灵的区域
	Vec2 beginPoint = touch->getLocation();
	//获取触摸的开始位置
	if (ballRect.containsPoint(beginPoint)){
		Point endPoint = touch->getPreviousLocation();
		//获取触摸的结束位置
		Point offSet = beginPoint - endPoint;
		//计算出两个位置的差
		Point newPosition = ball->getPosition() + offSet;
		//计算出精灵现在应该在的位置
		ball->setPosition(newPosition);
		//把精灵的位置设置到它应该在的位置
	}
}
这样即可实现基本的精灵跟随触摸位置移动。

不过这个方法有一定的问题,当快速移动时,精灵可能会丢失触摸的位置,需要重新点击并且移动才可以继续跟上手指。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值