快捷搜索: 王者荣耀 脱发

box2d学习之一鼠标关节及查询AABB

这两天在学习Box2d的关节 ,在网上看了一些资料但是还是没有解决我的问题(当点击鼠标并移动时,物体不跟着移动),所以自己看了下查询AABB的源码,总算明白了为什么我的鼠标关节没起作用。把代码贴在这里,留作参考i

部分代码如下

void HelloWorld::ccTouchesBegan(cocos2d::CCSet* touches, cocos2d::CCEvent* event) { if(m_pMouseJoint != NULL) return; CCSetIterator it; CCTouch* pTouch; for (it = touches->begin(); it != touches->end(); it++) { pTouch = (CCTouch*)(*it); if (!pTouch) { break; } CCPoint location = pTouch->getLocation(); CCPoint nodelocation = convertToNodeSpace(location);// CCDirector::sharedDirector()->conver(location); b2Vec2 p = b2Vec2(nodelocation.x/PTM_RATIO ,nodelocation.y/PTM_RATIO);//这里必须给出物理世界的坐标,如果不除以PTM_RATIO,物体的形状与所给的坐标永远不重合,一个晚上搞明白的,唉!!!!!! b2AABB aabb; 根据鼠标当前位置构建一个AABB , b2Vec2 d; d.Set(0.001f,0.001f); aabb.lowerBound = p - d; aabb.upperBound = p + d; QueryCallBack callback(p); 查询回调函数类继承b2QueryCallback ,该类有个纯虚方法,必须实现。 world->QueryAABB(&callback, aabb);查询与aabb重合的形状,如果有形状与aabb重合,就会调用 QueryCallBack的ReportFixture方法,告诉我们哪个形状与aabb重合,根据形状获取对应的物体,再对物体进行处理。 if (callback.m_fixture) { b2Body* body = callback.m_fixture->GetBody(); b2MouseJointDef md; md.bodyA = groundBody; md.bodyB = body; md.target = p; md.maxForce = 1000.0f * body->GetMass(); m_pMouseJoint = (b2MouseJoint*)world->CreateJoint(&md); body->SetAwake(true); return ; } // b2WorldQueryWrapper } } void HelloWorld::ccTouchesMoved(cocos2d::CCSet* touches, cocos2d::CCEvent* event) { if (m_pMouseJoint == NULL) { return; } CCSetIterator it; CCTouch *pTouch; for (it = touches->begin(); it != touches->end(); it++) { pTouch = (CCTouch*)(*it); if (!pTouch) { break; } CCPoint location = pTouch->getLocationInView(); location = CCDirector::sharedDirector()->convertToGL(location); b2Vec2 locationWorld = b2Vec2(location.x/PTM_RATIO , location.y/PTM_RATIO); m_pMouseJoint->SetTarget(locationWorld); } } void HelloWorld::ccTouchesEnded(CCSet* touches, CCEvent* event) { //Add a new body/atlas sprite at the touched location CCSetIterator it; CCTouch* touch; if (m_pMouseJoint != NULL) { world->DestroyJoint(m_pMouseJoint); m_pMouseJoint = NULL; } for( it = touches->begin(); it != touches->end(); it++) { touch = (CCTouch*)(*it); if(!touch) break; CCPoint location = touch->getLocationInView(); location = CCDirector::sharedDirector()->convertToGL(location); //addNewSpriteAtPosition( location ); } }

//*********************************************

class QueryCallBack :public b2QueryCallback { public: QueryCallBack(const b2Vec2& point) { m_point = point; m_fixture = NULL; } bool (b2Fixture* fixture) { b2Body* body = fixture->GetBody(); if (body->GetType() == b2_dynamicBody) { bool inside = fixture->GetBody(); if (inside) { m_fixture = fixture ; return false; } } return true; } b2Vec2 m_point; b2Fixture* m_fixture; };

经验分享 程序员 微信小程序 职场和发展