让子弹飞,图片缓冲应用

今天看到同学讲到图片缓冲的应用,原文(http://bbs.9ria.com/thread-61328-1-2.html)

看了下代码,发现还有改进的余地,特地自己实现了一把

 

改进的地方:改进beginBitmapFill为位图,这个比较耗,用vector代替arrary

不再传递buffer及位图,数据和具体显示分离

简化了部分代码

 

下面是具体效果

运动物品类

package {

	/**
	 * 运动物品类
	 * @author heycup@gmail.com
	 */
	public class MoveObject {
		public var x:int;
		public var y:int;
		public var sx:int;
		public var sy:int;

		public function update():void {
			x += sx;
			y += sy;
			if (x > BitmapBufferTest.w || x < 0){
				sx = -sx;
			}
			if (y > BitmapBufferTest.h || y < 0){
				sy = -sy;
			}
		}
	}
}

场景类

package {
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Point;

	/**
	 * ...
	 * @author heycup@gmail.com
	 */
	public class BitmapBufferTest extends Sprite {
		public static var w:int = 600;
		public static var h:int = 400;

		private var objects:Vector.<MoveObject> = new Vector.<MoveObject>();
		private var maxNum:uint = 5000;
		private var bmd:BitmapData;

		//嵌入子弹图片
		[Embed(source='../bin/zhidan.png')]
		private var ZhiDan:Class;
		private var zhidanBmd:BitmapData;

		public function BitmapBufferTest(){
			init();
		}

		private function init():void {
			//获取子弹的bitmapdata
			var zhidan:Bitmap = new ZhiDan();
			zhidanBmd = zhidan.bitmapData;
			
			//实例buffer
			bmd = new BitmapData(w, h, false, 0x000000);
			var bitmap:Bitmap = new Bitmap(bmd);
			addChild(bitmap);

			//实例大量子弹运动类
			for (var i:int = 0; i < maxNum; i++){
				var moveObject:MoveObject = new MoveObject();
				moveObject.x = w * Math.random();
				moveObject.y = h * Math.random();
				moveObject.sx = Math.random() * 5 + 1;
				moveObject.sy = Math.random() * 5 + 1;
				objects.push(moveObject);
			}
			//开始运动
			addEventListener(Event.ENTER_FRAME, onEnterFrame);
		}

		private function onEnterFrame(e:Event):void {			
			bmd.fillRect(bmd.rect, 0x000000);
			for (var i:int = 0, n:int = objects.length; i < n; i++){
				var item:MoveObject = objects[i];
				bmd.copyPixels(zhidanBmd, zhidanBmd.rect, new Point(item.x, item.y));
				item.update();
			}
		}
	}
}

cpu占用是0%

 

其实不清除面板更漂亮,效果:https://files.cnblogs.com/heycup/BitmapBufferTest2.swf

posted @ 2011-01-25 16:07  heycup  阅读(1022)  评论(1编辑  收藏  举报