读书人

Cocos2d-x Box2d札记 :关节的使用 mou

发布时间: 2012-09-16 17:33:16 作者: rapoo

Cocos2d-x Box2d笔记 :关节的使用 mouseJoint和PrismaticJoint

mouseJoint:

作用是实现鼠标拖拽的效果。

使用方法如下

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 touchedb2MouseJointDef 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了

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

这个就更简单 了

作用是限定一个物理的运动范围

//restrict paddleb2PrismaticJointDef jointDef;jointDef.collideConnected=true;b2Vec2 worldAxis(1.0f,0.0f);//这里限定在水平X轴的方向jointDef.Initialize(paddleBody,groundBody,paddleBody->GetWorldCenter(),worldAxis);//各个参数的意思是,被限定物体,限定的区域(一般是世界),限定点,方向world->CreateJoint(&jointDef);


读书人网 >操作系统

热点推荐