学习 Box2D 个人笔记(四)b2MouseJoint

这个玩意是干啥的呢 ,这个玩意是能拖动刚体的东西。也就是说 触摸的时候可以随着手指运动。首先 ,我们要有一个刚体 ,这个相信很多同学都会添加。

    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;
    }
   
}



这样就可以拖动物体拉。  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值