Skip to content

Instantly share code, notes, and snippets.

@alamboley
Last active October 12, 2015 11:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alamboley/4022129 to your computer and use it in GitHub Desktop.
Save alamboley/4022129 to your computer and use it in GitHub Desktop.
How to grab and drag physics objects (Citrus Engine recipe)
// In a state class :
//Here we use Box2D. /!\ Don't forget that your _hero must have its touchable property set to true!
var draggableHeroArt:DisplayObject = view.getArt(_hero) as DisplayObject;
draggableHeroArt.addEventListener(MouseEvent.MOUSE_DOWN, _handleGrab);
stage.addEventListener(MouseEvent.MOUSE_UP, _handleRelease);
private function _handleGrab(mEvt:MouseEvent):void {
var clickedObject:CitrusObject = view.getObjectFromArt(mEvt.currentTarget) as CitrusObject;
if (clickedObject)
_hero.enableHolding(mEvt.currentTarget.parent);
}
private function _handleRelease(mEvt:MouseEvent):void {
_hero.disableHolding();
}
// The DraggableHero class :
package{
import Box2D.Common.Math.b2Vec2;
import Box2D.Dynamics.Joints.b2MouseJoint;
import Box2D.Dynamics.Joints.b2MouseJointDef;
import com.citrusengine.objects.platformer.box2d.Hero;
import flash.display.DisplayObject;
public class DraggableHero extends Hero{
private var _jointDef:b2MouseJointDef;
private var _joint:b2MouseJoint;
private var _mouseScope:DisplayObject;
public function DraggableHero(name:String, params:Object = null) {
touchable = true;
super(name, params);
}
override public function destroy():void {
if (_joint)
_box2D.world.DestroyJoint(_joint);
super.destroy();
}
override public function update(timeDelta:Number):void {
super.update(timeDelta);
if (_joint) {
_joint.SetTarget(new b2Vec2(_mouseScope.mouseX / _box2D.scale, _mouseScope.mouseY / _box2D.scale));
}
}
public function enableHolding(mouseScope:DisplayObject):void {
if (_joint)
return;
_mouseScope = mouseScope;
_jointDef.target = new b2Vec2(_mouseScope.mouseX / _box2D.scale, _mouseScope.mouseY / _box2D.scale);
_joint = _box2D.world.CreateJoint(_jointDef) as b2MouseJoint;
}
public function disableHolding():void {
if (!_joint)
return;
_box2D.world.DestroyJoint(_joint);
_joint = null;
}
override protected function defineFixture():void {
super.defineFixture();
_fixtureDef.density = 0.1;
}
override protected function defineJoint():void {
super.defineJoint();
_jointDef = new b2MouseJointDef();
_jointDef.bodyA = _box2D.world.GetGroundBody();
_jointDef.bodyB = _body;
_jointDef.dampingRatio = .2;
_jointDef.frequencyHz = 100;
_jointDef.maxForce = 100;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment