您的位置:首页 > 移动开发 > Cocos引擎

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

2015-07-27 12:46 513 查看
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);
//把精灵的位置设置到它应该在的位置
}
}这样即可实现基本的精灵跟随触摸位置移动。
不过这个方法有一定的问题,当快速移动时,精灵可能会丢失触摸的位置,需要重新点击并且移动才可以继续跟上手指。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Cocos2d-x