转至:http://www.klstudio.com/post/119.html
package { import flash.display.*; import flash.net.*; import flash.utils.Timer; import flash.events.*; import flash.geom.*; public class GameSprite extends Sprite { private var timer:Timer; private var sWidth:uint; private var sHeight:uint; private var sStep:uint; private var sDirection:uint; private var loader:Loader; private var maps:Array; private var pointer:uint; private var map:Bitmap; function GameSprite() { //角色大小; sWidth = 100; sHeight = 100; //角色移动方向; sDirection = 0; //角色步数; sStep = 1; //角色动作数组; maps = new Array(); //初始化角色动作运行指针; pointer = 0; //初始化time; timer = new Timer(100); timer.addEventListener(TimerEvent.TIMER, timerHandler); //图片加载对象; loader = new Loader(); loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler); loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, errorHandler); loader.load(new URLRequest("/download/sprite.png")); stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler); } //错误处理事件; private function errorHandler(event:IOErrorEvent):void { trace("IOErrorEvent"); } //键盘事件,通过方向键更改角色移动方向; private function keyDownHandler(event:KeyboardEvent):void { switch (event.keyCode) { case 40 : sDirection = 0; break; case 38 : sDirection = 3; break; case 37 : sDirection = 1; break; case 39 : sDirection = 2; break; } } //定时器运行事件; private function timerHandler(event:Event):void { //删除旧的角色动作图像; if (map != null) { removeChild(map); } //显示新的角色动作图像; map = new Bitmap(maps[sDirection][pointer]); addChild(map); //角色动作循环处理; if (pointer < sStep-1) { pointer ++; } else { pointer = 0; } } //加载图片完成处理事件; private function completeHandler(event:Event):void { //根据图片的大小初始化BitmapData; /* * 注意如果你要保留原来的图片的透明度的话,必将transparent设置为true,同时设置填充色值的前两位为00; */ var sBmd:BitmapData = new BitmapData(loader.width,loader.height,true,0x00FFFFFF); sBmd.draw(loader); //计算移动步数; sStep = Math.floor(loader.width/sWidth); for (var j:uint = 0; j<Math.floor(loader.height/sHeight); j++) { var arr:Array = new Array(); for (var i:uint = 0; i<sStep; i++) { var bmd:BitmapData = new BitmapData(sWidth,sHeight,true,0x00FFFFFF); //获取单个角色的BitmapData对象; bmd.copyPixels(sBmd,new Rectangle(sWidth*i, sHeight*j, sWidth, sHeight),new Point(0,0)); arr.push(bmd); } //放入角色数组里; maps.push(arr); } //释放sBmd资源; sBmd.dispose(); //开始运行角色动作; timer.start(); } } }