Cocos2d-x Box2d笔记 :关节的使用 mouseJoint和PrismaticJoint
mouseJoint:
作用是实现鼠标拖拽的效果。
使用方法如下
[cpp]
void HelloWorld::ccTouchesBegan(CCSet *touches, CCEvent *pEvent)
{
//CCLOG("touchBegan");
if(mouseJoint!=NULL)
return;
CCLOG("touchBegan");
CCSetIterator it;
CCTouch* touch;
for( it = touches->begin(); it != touches->end(); it++)
{
touch = (CCTouch*)(*it);
if(!touch)
break;
CCPoint location = touch->locationInView();
location = CCDirector::sharedDirector()->convertToGL(location);
b2Vec2 locationWorld=b2Vec2(location.x/PTM_RATIO,location.y/PTM_RATIO);
//这里取得触摸的坐标
if(paddleFixeture->TestPoint(locationWorld))//判断是否在触摸范围
{
//if touched
b2MouseJointDef md;
md.bodyA=groundBody;//一般为世界边界
md.bodyB=paddleBody;//需要拖动的物体
md.target=locationWorld;//指定拖动的坐标
md.collideConnected=true; //
md.maxForce=1000.0f*paddleBody->GetMass(); //给一个拖动的力
mouseJoint=(b2MouseJoint*)world->CreateJoint(&md);//创建
paddleBody->SetAwake(true);//
CCLOG("touchBegan");
}
}
}
上面就定义了mouseJoint的参数
然后再在touchedMoved里面时时改变坐标就OK了
[cpp]
void HelloWorld::ccTouchesMoved(CCSet *touches, CCEvent *pEvent)
{
if(mouseJoint==NULL)
return;
CCSetIterator it;
CCTouch* touch;
for( it = touches->begin(); it != touches->end(); it++)
{
touch = (CCTouch*)(*it);
if(!touch)
break;
CCPoint location = touch->locationInView();
location = CCDirector::sharedDirector()->convertToGL(location);
b2Vec2 locationWorld=b2Vec2(location.x/PTM_RATIO,location.y/PTM_RATIO);
mouseJoint->SetTarget(locationWorld);
}
}
最后记得在touchedEnded里面加上这句释放
if(mouseJoint!=NULL)
{
world->DestroyJoint(mouseJoint);
mouseJoint=NULL;
}
PrismaticJoint
这个就更简单 了
作用是限定一个物理的运动范围
[cpp]
//restrict paddle
b2PrismaticJointDef jointDef;
jointDef.collideConnected=true;
b2Vec2 worldAxis(1.0f,0.0f);//这里限定在水平X轴的方向
jointDef.Initialize(paddleBody,groundBody,paddleBody->GetWorldCenter(),worldAxis);//各个参数的意思是,被限定物体,限定的区域(一般是世界),限定点,方向
world->CreateJoint(&jointDef);
补充:移动开发 , 其他 ,