用了两种关节,距离关节和鼠标关节,距离关节是用约束两个刚体的,算是最简单的一种,初始化很简单:
var disj:b2DistanceJointDef =new b2DistanceJointDef(); disj.Initialize(poly, poly2, new b2Vec2(15, 3), new b2Vec2(17, 9)); var dis:b2DistanceJoint = world.CreateJoint(disj ) as b2DistanceJoint;
鼠标关节用来拖动刚体。
private function mousedrag():void { if (mousedown&&!mouseJoint) { var bodyy:b2Body = getBodyAtMouse(); if (bodyy) { var md:b2MouseJointDef = new b2MouseJointDef(); md.bodyA = world .GetGroundBody(); md.bodyB = bodyy; md.target.Set(mousepx ,mousepy); md.collideConnected = true; md.maxForce = 1000.0 * bodyy.GetMass(); mouseJoint = world.CreateJoint(md) as b2MouseJoint; bodyy.SetAwake(true); } } if (!mousedown) { if (mouseJoint) { world .DestroyJoint(mouseJoint ); mouseJoint = null; } } if (mouseJoint) { mouseJoint.SetTarget(new b2Vec2(mousepx, mousepy)); } }
getBodyAtMouse()用来查找位于鼠标下的刚体,
private function getBodyAtMouse(includeStatic:Boolean = false):b2Body { //创建一个小的边界区域 _mousePVec.Set(mousepx ,mousepy); var aabb:b2AABB = new b2AABB(); aabb.lowerBound.Set(mousepx - 0.001,mousepy - 0.001); aabb.upperBound.Set(mousepx + 0.001,mousepy + 0.001); var bodyyy:b2Body = null; var fixture:b2Fixture; //回调函数的形式获取鼠标下面的刚体 function getBodyCallback(fixture:b2Fixture):Boolean { var shape:b2Shape = fixture.GetShape(); if(fixture.GetBody().GetType() != b2Body.b2_staticBody || includeStatic) { var inside:Boolean = shape.TestPoint(fixture.GetBody().GetTransform(),_mousePVec); if(inside) { bodyyy= fixture.GetBody(); return false; } } return true; } world.QueryAABB(getBodyCallback, aabb); return bodyyy; }