Game Development Reference
In-Depth Information
We start by adding the mouse event listener to the
PieceSprite
class. When a
mouse down is detected, we record the current position of the piece.
private function mouseDownHandler(event:MouseEvent):void {
//trace("mouseDownHandler");
//var sprite:Sprite = Sprite(event.target);
PieceCutter.getInstance().bringToFront(this);
m_sprite.addEventListener(MouseEvent.MOUSE_MOVE,
mouseMoveHandler);
m_dsx = m_sprite.x;
m_dsy = m_sprite.y;
m_sprite.startDrag();
}
We also subscribe to the mouse move event.
private function mouseMoveHandler(event:MouseEvent):void {
//trace("mouseMoveHandler");
var sprite:Sprite = Sprite(event.target);
m_group.move((m_sprite.x-m_dsx), (m_sprite.y-m_dsy),
this);
m_dsx = m_sprite.x;
m_dsy = m_sprite.y;
event.updateAfterEvent();
}
In the mouse move handler, we call the move method on the group that will move
all the pieces in the group by the delta, which is the difference between the sprite's
current position and the last recorded position (
m_dsx
and
m_dsy
). After we have
moved the sprites, we reset the
m_dsx
and
m_dsy
to the current position.
The
move
method in the Group class is shown as follows:
public function move(dx:Number,
dy:Number,
skip:PieceSprite):void {
var i:int=0;
//trace("Group move: " + m_pieces.length);
for ( i=0; i<m_pieces.length; i++ ) {
var p:PieceSprite = m_pieces[i];
if ( skip != null && p == skip )
continue;
p.move(dx, dy);
}
}
Note that we skipped the piece that is being held by the player, as Flash takes care of
moving it for us already.