July 08, 2009

Drag the Sprite using the Shift Key and Mouse Down event in AS3

Hi,
This following example for drag the sprite when holding the shift key in the Keyboard. The Shify key was released then the sprite cannot be moved furtur and it stop drag into the selected dragged area. The selected sprite should be focus then only it can work the functionality of the keyboard and check whether pressed the shift key or not. The Display object cannot be focus use the code as stage.focus property as currently selected Display object. This property helps to focus the current Display object selection and then drag the sprite based on Shift Key was pressed.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" applicationComplete="onKeySet()" creationComplete="onInit()">
<mx:Script>
<![CDATA[
import mx.core.UIComponent;
private var _spr:Sprite;

private function onInit():void
{
var ui:UIComponent = new UIComponent();
_spr = new Sprite();
_spr.graphics.clear();
_spr.graphics.beginFill(0xFF0000,0.7);
_spr.graphics.drawRect(0,0,500,500);
_spr.graphics.endFill();
ui.addChild(_spr);
addChild(ui);
}

private function onKeySet():void
{
stage.addEventListener(KeyboardEvent.KEY_DOWN,onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP,onKeyUp);
}

private function onKeyDown(evt:KeyboardEvent):void
{
stage.focus = _spr;
_spr.focusRect = false;
if(evt.keyCode == 16)
{
_spr.addEventListener(MouseEvent.MOUSE_DOWN,onDownSprite);
_spr.addEventListener(MouseEvent.MOUSE_UP,onUpSprite);
}
}

private function onKeyUp(evt:KeyboardEvent):void
{
if(evt.keyCode == 16)
{
_spr.removeEventListener(MouseEvent.MOUSE_DOWN,onDownSprite);
_spr.removeEventListener(MouseEvent.MOUSE_UP,onUpSprite);
}
}

private function onDownSprite(evt:MouseEvent):void
{
_spr.addEventListener(MouseEvent.MOUSE_MOVE,onMoveSprite);
}

private function onMoveSprite(evt:MouseEvent):void
{
_spr.startDrag();
evt.updateAfterEvent();
}

private function onUpSprite(evt:MouseEvent):void
{
_spr.stopDrag();
_spr.removeEventListener(MouseEvent.MOUSE_MOVE,onMoveSprite);
}

]]>
</mx:Script>
</mx:Application>

No comments:

Post a Comment