As3 box2d 鼠标关节
知识要点:
1,怎么获取鼠标坐标点下的刚体
2,创建鼠标关节 b2MouseJoint
3, b2World.GetGroundBody()方法
GetGroundBody | () | method |
public function GetGroundBody():b2Body
The world provides a single static ground body with no collision shapes. You can use this to simplify the creation of joints and static shapes.
此方法提供了一个静态的地面刚体,不包含碰撞图形,可以单纯的用他来建立关节和静态的图形
private function updateMouseWorld()
{
_mouseX = this.mouseX;
_mouseY = this.mouseY;
mouseXPhy = _mouseX / PIXEL_TO_METER;
mouseYphy = _mouseY / PIXEL_TO_METER;
}
private function getBody():b2Body
{
mousePVec2.Set(mouseXPhy, mouseYphy);
//创建一个区域
var aabb:b2AABB = new b2AABB();
aabb.lowerBound.Set(mouseXPhy - 0.001, mouseYphy - 0.001);
aabb.upperBound.Set(mouseXPhy - 0.001, mouseYphy - 0.001);
var body:b2Body;
//使用一个回调函数/查看api b2word.Queryy(,,/,,)
function getBodyCallback(fixture:b2Fixture):Boolean
{
var shape:b2Shape = fixture.GetShape();
if (fixture.GetBody().GetType() != b2Body.b2_staticBody)
{
var inside:Boolean = shape.TestPoint(fixture.GetBody().GetTransform(), mousePVec2);
if (inside)
{
body = fixture.GetBody();
return false; //不进行下个fixture检查了
}
}
return true;
}
world.QueryAABB(getBodyCallback, aabb);
return body;
}
private function mouseDrag()
{
if (bMouseDown && !mouseJoint)
{
var body:b2Body = getBody();
if (body)
{
trace("has a body");
var mouseJointDef:b2MouseJointDef = new b2MouseJointDef();
mouseJointDef.bodyA = world.GetGroundBody();
mouseJointDef.bodyB = body;
mouseJointDef.target.Set(mouseXPhy, mouseYphy);//设置关节的目标使用是物理世界鼠标位置
mouseJointDef.collideConnected = true;
mouseJointDef.maxForce = 100 * body.GetMass();//300*刚体质量
mouseJoint = world.CreateJoint(mouseJointDef) as b2MouseJoint;
}
}
if (!bMouseDown)//鼠标松开销毁关节
{
if (mouseJoint)
{
world.DestroyJoint(mouseJoint);
mouseJoint = null;
}
}
if (mouseJoint)//如果有了鼠标关节 目标始终指向
{
mouseJoint.SetTarget(new b2Vec2(mouseXPhy,mouseYphy));
}