这个玩意是干啥的呢 ,这个玩意是能拖动刚体的东西。也就是说 触摸的时候可以随着手指运动。首先 ,我们要有一个刚体 ,这个相信很多同学都会添加。
b2Body * spriteBody;
而且将这个刚体初始化,添加到世界里。然后,我们在这个前提下,来操作移动刚体 ,如果不会添加刚体,移步到 如何新建一个Body。
接下来,我们要随手指移动 ,那么首先要在init里面添加:
setTouchEnabled(true);
然后在类里面添加成员:
b2MouseJoint *_mouseJoint;
然后重写touch方法:
virtual void ccTouchesEnded(cocos2d::CCSet* touches, cocos2d::CCEvent* event);
virtual void ccTouchesBegan(cocos2d::CCSet* touches, cocos2d::CCEvent* event);
virtual void ccTouchesMoved(cocos2d::CCSet* touches, cocos2d::CCEvent* event);
然后实现这些方法:
void HelloWorld::ccTouchesBegan(CCSet *touches,CCEvent *event)
{
CCTouch* touch = (CCTouch*)touches->anyObject();
CCPoint location = touch->getLocationInView();
location = CCDirector::sharedDirector()->convertToGL(location);
b2Vec2 locationWorld = b2Vec2::b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);
if (spriteBody->GetFixtureList()->TestPoint(locationWorld)) {
b2MouseJointDef md;
md.bodyA = groundBody; //一般为世界边界
md.bodyB = spriteBody; //要拖动的物体
md.target = locationWorld; //设置关节的坐标
md.collideConnected = true; //如果设成false 那么在物体拖动的时候物体与边界,也就是groundBody无碰撞
md.maxForce =1000.0f* spriteBody->GetMass(); //设置力的大小
_mouseJoint = (b2MouseJoint*)world->CreateJoint(&md); // 创建关节
}
}
void HelloWorld::ccTouchesMoved(CCSet* touches, CCEvent* event)
{
CCTouch* touch = (CCTouch*)touches->anyObject();
CCPoint location = touch->getLocationInView();
location = CCDirector::sharedDirector()->convertToGL(location);
b2Vec2 locationWorld = b2Vec2::b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);
if (_mouseJoint) //判断 否则会找不到 然后报错
_mouseJoint->SetTarget(locationWorld);
}
void HelloWorld::ccTouchesEnded(CCSet* touches,CCEvent* event)
{
if (_mouseJoint) //判断 否则会找不到 然后报错
{
world->DestroyJoint(_mouseJoint); //摧毁关节
_mouseJoint = NULL;
}
}