Friday, 18 May 2012

Drag and drop in AS3 Starling

In this quick post I will provide code for dragging and dropping in the Starling framework for Actionscript 3. I will be using the native Quad as an example. Here is my Main and Game class.

package 
{
 import starling.core.Starling;
 import flash.display.Sprite;
 import flash.display.StageAlign;
 import flash.display.StageScaleMode;

 [SWF(width="550", height="400", frameRate="60", backgroundColor="#CCCCCC")]
 
 public class Main extends Sprite
 {
  private var mStarling:Starling;
   
  public function Main()
  {
   stage.scaleMode = StageScaleMode.NO_SCALE;
   stage.align = StageAlign.TOP_LEFT;
  
   mStarling = new Starling(Game, stage);
   mStarling.antiAliasing = 2;
   mStarling.start();
  }
 }
}
I have added the Quad display object to the centre of the stage with the touch event listener. The touchHandler function detects mouse down and mouse move events and moves the Quad object to the mouse’s x and y positions. I have offset the position by half the width and height of the Quad, so that it gets dragged and dropped from the centre of the object.
package {

 import starling.events.TouchPhase;
 import flash.geom.Point;
 import starling.events.Touch;
 import starling.events.TouchEvent;
 import starling.events.Event;
 import starling.display.Quad;
 import starling.display.Sprite;

 public class Game extends Sprite {
  
  public function Game() {
   addEventListener(Event.ADDED_TO_STAGE, onAdded);
  }
  
  private function onAdded (e:Event):void { 
   var q:Quad = new Quad(50,50);
   q.x = stage.stageWidth/2 - q.width/2;
   q.y = stage.stageHeight/2 - q.height/2;
   q.addEventListener(TouchEvent.TOUCH, touchHandler); 
   addChild(q);
  }

  private function touchHandler(e : TouchEvent) : void 
  {
   var touch:Touch = e.getTouch(stage);
   var position:Point = touch.getLocation(stage);
   var target:Quad = e.target as Quad;
   
   if(touch.phase == TouchPhase.MOVED ){
    target.x = position.x - target.width/2;
    target.y = position.y - target.height/2;
   }
  }
 }
}
The same works if you have multiple objects to drag and drop. This code uses a for Loop to add 10 Quad objects randomly on the stage with the touch event listener.
for(var i:uint = 0; i < 10; i++){
 var q:Quad = new Quad(50,50);
 q.color = Math.random() * 0xFFFFFF;
 q.x = Math.random() * stage.stageWidth - q.width;
 q.y = Math.random() * stage.stageHeight - q.height;
 q.addEventListener(TouchEvent.TOUCH, touchHandler); 
 addChild(q);
} 
If you want to check the memory usage of your Starling app there are two classes you can use, look at this post for more information.

0 comments:

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP