咱們能夠經過鼠標聯合點擊、操做世界裏面的剛體。鼠標聯合的原理是當鼠標點擊剛體時,給隱藏的一個鼠標Sprite(位置和當前鼠標相同)和點擊的剛體建立一根聯合線(Joint Line),該聯合線的特色是剛體會沿着聯合線運動,而鼠標的移動就是改變聯合線。ide
鼠標點擊剛體獲取所選剛體的步驟:函數
var mouseXWorldPhys:Number = mouseX / worldScale; var mouseYWolrdPhys:Number = mouseY / worldScale;
var mousePVec2:b2Vec2 = new b2Vec2(); mousePVec2.Set(mouseXWorldPhys,mouseYWorldPhys);
或者spa
var mousePVec2:b2Vec2 = new b2Vec2(mouseXWorldPhys,mouseYWorldPhys);
var aabb:b2AABB = new b2AABB(); aabb.lowerBound.Set(mouseXWorldPhys-0.001,mouseYWorldPhys-0.001); aabb.upperBound.Set(mouseXWorldPhys+0.001,mouseYWorldPhys+0.001);
/**Query the world for all fixtures that potentially overlap the provided AABB. */ //Parameters //callback:Function — a user implemented callback class. It should match signature function //Callback(fixture:b2Fixture):Boolean Return true to continue to the next fixture. //aabb:b2AABB — the query box.
核心代碼以下:code
private function GetBodyAtMouse(includeStatic:Boolean = false):b2Body { mousePVec2.Set(mouseXWorldPhys, mouseYWorldPhys); var aabb:b2AABB = new b2AABB(); aabb.lowerBound.Set(mouseXWorldPhys - 0.001, mouseYWorldPhys - 0.001); aabb.upperBound.Set(mouseXWorldPhys + 0.001, mouseYWorldPhys + 0.001); var body:b2Body; 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(), mousePVec2); if (inside) { body = fixture.GetBody(); return false; } } return true; } world.QueryAABB(getBodyCallback, aabb); return body; }