当前位置: > > > AS3 - 简单小游戏(点击生成小球,小球会自动移动碰撞)

AS3 - 简单小游戏(点击生成小球,小球会自动移动碰撞)

下面是一个使用as3开发的简单游戏demo,实现的功能如下:
1,鼠标每点击一次生成一个小球
2,小球会自动运动,碰到墙壁会反弹
3,背景通过文本框显示当前舞台元件数,以及帧数

效果图如下:


--- 主界面 Main.as ---
package {
	import flash.display.Bitmap;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	import flash.utils.getTimer;
	
	[SWF( width="680", height="483")]
	public class Main extends Sprite
	{
		// 定义嵌入图片类
		[Embed(source="bg.png")]
		private var BackClass:Class;
		// tCount用于显示Sprite的个数,tFrameRate用于显示帧率
		private var tCount:TextField, tFrameRate:TextField;
		public function Main()
		{
			// 构造背景图片
			var bak:Bitmap = new BackClass() as Bitmap;
			addChild(bak);
			// 创建两个TextField用于显示Sprite个数和帧率
			tCount = new TextField();
			tCount.x = 20;
			tCount.y = 20;
			tFrameRate = new TextField();
			tFrameRate.x = 120;
			tFrameRate.y = 20;
			addChild(tCount);
			addChild(tFrameRate);
			
			// 添加鼠标事件(用于生成新的小球)
			parent.addEventListener(MouseEvent.MOUSE_UP, clickHandler);
			// 添加帧开始事件(用于统计帧率)
			parent.addEventListener(flash.events.Event.ENTER_FRAME, enterFrame);
		}
		
		// 当鼠标按钮松开时,增加一个小球
		public function clickHandler(e:MouseEvent):void 
		{
			var t:BallSprite = new BallSprite();
			
			t.x = e.stageX;
			t.y = e.stageY;
			addChild(t);
		}        
		
		private var old:Number = 0, framecount:Number = 0;
		
		// 统计并显示Sprite个数和帧率
		public function enterFrame(e:Event):void
		{
			tCount.text = "Sprites:" + String(this.numChildren);
			
			framecount ++;
			
			if(old == 0)
			{
				old = getTimer();
				return;
			}
			var temp:Number = getTimer();
			var ms:Number = temp - old;
			if(ms > 1000)
			{
				var rate:Number = framecount*1000 / ms;
				old = temp;
				framecount = 0;
				tFrameRate.text = "FPS:" + String(rate).substring(0, 7);
			}            
			
		}
	}
}

--- 小球 BallSprite.as ---
package
{
	import flash.display.Sprite;
	import flash.utils.setInterval;
	
	public class BallSprite extends Sprite
	{
		[Embed(source="ball.png")]
		private var BallClass: Class;
		
		public function BallSprite()
		{        
			addChild(new BallClass());
			// 设置定时事件
			setInterval(timerHandler, 1000/30);
		}
		
		private var d:Number = 5, dx:Number = d, dy:Number = d;
		
		// 定时让小球移动
		public function timerHandler():void 
		{
			var pw:Number = parent.getChildAt(0).width;
			var ph:Number = parent.getChildAt(0).height;
			x += dx; y += dy;
			if(x <= 0) dx = d;
			if(x >= pw-width) dx = -d;
			if(y <= 0) dy = d;
			if(y >= ph-height) dy = -d;                
		}
	}
}
评论0