Box2D引擎與觸摸的交互經過建立鼠標關節以及碰撞檢測來獲得觸摸點下面的剛體,在根據觸摸操做完成相應的功能。首先添加觸摸響應函數聲明ide
virtual void ccTouchesBegan(cocos2d::CCSet* touches, cocos2d::CCEvent* event); virtual void ccTouchesMoved(cocos2d::CCSet* touches, cocos2d::CCEvent* event); virtual void ccTouchesEnded(cocos2d::CCSet* touches, cocos2d::CCEvent* event);
聲明一個鼠標關節變量函數
b2World* world; b2Body* wallBody ; float32 wallLineOffset ; b2MouseJoint* m_MouseJoint; //鼠標關節 GLESDebugDraw* m_debugDraw; //調試物理世界繪製對象
在init中打開觸摸功能this
m_MouseJoint = NULL; this->setTouchEnabled(true);
建立一個碰撞查詢回調類spa
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; };
實現觸摸函數debug
void HelloWorld::ccTouchesBegan(CCSet* touches, CCEvent* event){ CCSetIterator it; CCTouch* touch; for( it = touches->begin(); it != touches->end(); it++) { touch = (CCTouch*)(*it); if(!touch) break; CCPoint location = touch->getLocation(); if (m_MouseJoint != NULL) return ; // 根據觸摸點建立一個很小的碰撞檢測矩形 b2AABB aabb; b2Vec2 d; b2Vec2 p = b2Vec2(location.x/PIXEL_TO_METER,location.y/PIXEL_TO_METER); d.Set(0.001f, 0.001f); aabb.lowerBound = p - d; aabb.upperBound = p + d; // 查詢物理世界中的碰撞的剛體,回調對象(QueryCallback)中已通過濾的非動態物體 QueryCallback callback(p); world->QueryAABB(&callback, aabb); if (callback.m_fixture) { b2Body* body = callback.m_fixture->GetBody(); //爲獲取到的剛體建立一個鼠標關節 b2MouseJointDef md; md.bodyA = wallBody; md.bodyB = body; md.target = p; md.maxForce = 1000.0f * body->GetMass(); m_MouseJoint = (b2MouseJoint*)world->CreateJoint(&md); body->SetAwake(true); //喚醒剛體 } } } void HelloWorld::ccTouchesMoved(CCSet* touches, CCEvent* event){ CCSetIterator it; CCTouch* touch; for( it = touches->begin(); it != touches->end(); it++) { touch = (CCTouch*)(*it); if(!touch) break; CCPoint location = touch->getLocation(); if (m_MouseJoint) { //更新剛體的位置 m_MouseJoint->SetTarget(b2Vec2(location.x/PIXEL_TO_METER,location.y/PIXEL_TO_METER)); } } } void HelloWorld::ccTouchesEnded(CCSet* touches, CCEvent* event) { if (m_MouseJoint) { //觸摸結算銷燬鼠標關節 world->DestroyJoint(m_MouseJoint); m_MouseJoint = NULL; } }
最後看看運行效果調試