/************************************************************************/
/* QueryCallback */
/************************************************************************/
class QueryCallback : public b2QueryCallback
{
public:
QueryCallback(const b2Vec2& point)
{
m_point = point;
m_fixture = NULL;
}
bool ReportFixture(b2Fixture* fixture)
{
b2Body* body = fixture->GetBody();
if (body->GetType() == b2_dynamicBody)
{
bool inside = fixture->TestPoint(m_point);
if (inside)
{
m_fixture = fixture;
// We are done, terminate the query.
return false;
}
}
// Continue the query.
return true;
}
b2Vec2 m_point;
b2Fixture* m_fixture;
};
bool HelloWorld::MouseDown(const b2Vec2& p)
{
if (m_mouseJoint != NULL)
{
return false;
}
// Make a small box.
b2AABB aabb;
b2Vec2 d;
d.Set(0.001f, 0.001f);
aabb.lowerBound = p - d;
aabb.upperBound = p + d;
// Query the world for overlapping shapes.
QueryCallback callback(p);
world->QueryAABB(&callback, aabb);
if (callback.m_fixture)
{
b2Body* body = callback.m_fixture->GetBody();
b2MouseJointDef md;
md.bodyA = m_groundBody;
md.bodyB = body;
md.target = p;
md.maxForce = 1000.0f * body->GetMass();
m_mouseJoint = (b2MouseJoint*)world->CreateJoint(&md);
body->SetAwake(true);
return true;
}
}
void HelloWorld::MouseMove(const b2Vec2& p)
{
//m_mouseWorld = p;
if (m_mouseJoint)
{
m_mouseJoint->SetTarget(p);
}
}
void HelloWorld::MouseUp(const b2Vec2& p)
{
if (m_mouseJoint)
{
world->DestroyJoint(m_mouseJoint);
m_mouseJoint = NULL;
}
}
/*一下是为了测试移动整个世界*/
virtual bool MouseDown(const b2Vec2& p);
virtual void MouseUp(const b2Vec2& p);
void MouseMove(const b2Vec2& p);
// b2Vec2 m_mouseWorld;
b2MouseJoint* m_mouseJoint;
b2Body *m_groundBody;//空的b2body,为了给鼠标关节设置刚体A
bool HelloWorld::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
{
isStart = pTouch->getLocation();
CCPoint nodePosition = convertToNodeSpace( isStart );
//PTM_RATIO = 32
return MouseDown(b2Vec2(nodePosition.x / PTM_RATIO, nodePosition.y / PTM_RATIO));
}
void HelloWorld::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent)
{
CCPoint start = pTouch->getLocation();//get the coordinate of the touch point in openGL
CCPoint nodePosition = convertToNodeSpace( start );
this->MouseMove(b2Vec2(nodePosition.x / PTM_RATIO, nodePosition.y / PTM_RATIO));
}
void HelloWorld::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent)
{
CCPoint nodePosition = convertToNodeSpace( pTouch->getLocation() );
this->MouseUp(b2Vec2(nodePosition.x / PTM_RATIO,nodePosition.y / PTM_RATIO));
}