News:Starling中的拖拽
来自Starling中文站
http://www.ilike2flash.com/2012/05/drag-and-drop-in-as3-starling.html
翻译:郭少瑞
在这个简单的教程中,我将提供基于Starling框架实现拖拽的代码。我将使用Quad类来做演示。这是我的主类代码:
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(); } } }
我添加了一个Quad显示对象到stage的中心位置,并添加了触碰事件侦听。touchHandler方法将侦听鼠标按下和鼠标移动事件,并且移动Quad对象到光标的x和y坐标。同时我也添加了一个偏移量(Quad宽度和高度的一半),所以我在拖拽的时候,始终围绕对象的中心点进行操作。
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; } } } }
这种方法也同样适用于您处理多个对象的拖拽。下面的代码使用了for循环增加了10个Quad对象,并随机放置在stage某处,然后同样也具备touch事件侦听。
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); }
如果您想监控应用的内存使用情况,可以参考这里。
BTW:网友@令狐冲指出:最后一步关于多个拖拽的 如果只对Starling.current.stage侦听 然后取e.target 无须单独对每个Quad的侦听 这个方法也是可行的。
翻译:郭少瑞