cocos2d-x 鼠标或手指移动刚体

/************************************************************************/
/*              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));
}



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值