マウスジョイントを使って車を持ち運ぶ
ただ車が走っているだけではつまらないので,
クラスにプロパティを追加する
まず準備段階として,
// 物理エンジンの管理クラス
private var world:b2World; // ← この行までは最初からある
// 車体
private var body:b2Body;
// マウスジョイントの定義
private var mouseJointDef:b2MouseJointDef;
// マウスジョイント
private var mouseJoint:b2MouseJoint;
このうち,
var body:b2BodyDef = world.CreateDynamicBody(bodyDef);
↓ 書き換える
body = world.CreateDynamicBody(bodyDef);
mouseJointDefとmouseJointは,
マウスジョイントを定義する
車を作り終わった直後のところに,
// マウスジョイントを定義する
mouseJointDef = new b2MouseJointDef();
// 片方のbodyにはワールド全体を設定する
mouseJointDef.body1 = world.GetGroundBody();
// もう片方には移動させたい物体(=車体)を設定する
mouseJointDef.body2 = body;
// 車体の中心座標を設定する
mouseJointDef.target = body.GetWorldCenter();
// マウスで引っ張られるときの力
mouseJointDef.maxForce = 5;
// シミュレーションの間隔
mouseJointDef.timeStep = 1 / 24;
回転ジョイントのときと同じように,
targetには,
maxForceとtimeStepは,
マウスイベントのハンドラを追加する
ここまで書いて気づいたかもしれませんが,
マウス操作が絡んでくるので,
stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
マウスジョイントを作る
マウスボタンが押されたときに,
private function mouseDownHandler(event:MouseEvent):void {
// マウスボタンが押されたら,マウスジョイントを作る
mouseJoint = b2MouseJoint(world.CreateJoint(mouseJointDef));
}
マウスジョイントを切り離す
重要なのはマウスボタンが離されたときで,
private function mouseUpHandler(event:MouseEvent):void {
// マウスボタンが離されたら,マウスボタンを切り離す
world.DestroyJoint(mouseJoint);
mouseJoint = null;
}
マウスジョイントの位置を更新する
最後に,
private function mouseMoveHandler(event:MouseEvent):void {
// mouseJointがnullでないときだけ処理を実行する
if (mouseJoint) {
// マウスが押された場所を物理エンジン内の座標系に変換する
var x:Number = event.stageX / DRAW_SCALE;
var y:Number = event.stageY / DRAW_SCALE;
// マウスジョイントのカーソル位置を更新
mouseJoint.SetTarget(new b2Vec2(x, y));
}
}
これで完成です。コンパイルすると以下のようなFlashができると思います。画面上部でマウスを適当にドラッグすると,
ここまで編集してきたソースを,
まとめ
6種類あるジョイントの中から回転ジョイントとマウスジョイントを使い,
次回は脱DebugDrawをテーマに,