flash on 2010-2-20

by summerTree
简单小球重力模拟
夏天的树人
♥0 | Line 92 | Modified 2010-02-20 13:36:18 | MIT License
play

ActionScript3 source code

/**
 * Copyright summerTree ( http://wonderfl.net/user/summerTree )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/cYnS
 */

package 
{
	//简单小球重力模拟
	//夏天的树人
	import flash.display.Sprite;
	import flash.events.*;

	public class Main extends Sprite
	{
		private var g:Number=1;//重力
		private var friction:Number=0.98;//空气阻力
		private var contain:Sprite=new Sprite();//容器 
		private var list:Array=new Array();

		public function Main()
		{
			init();
		}
		private function init():void
		{
			addChild(contain);
			creatBalls(20);
			addEventListener(Event.ENTER_FRAME,Run);
			var btn:MyButton=new MyButton();
			btn.x=400;
			btn.y=50;
			btn.addEventListener(MouseEvent.MOUSE_DOWN,onDownHandler);
			addChild(btn);
			
		}
		private function onDownHandler(event:MouseEvent):void
		{
			while(list.length>0)list.pop();
			while(contain.numChildren>0)contain.removeChildAt(0);
			creatBalls(20);//创建小球			
		}
		
		
		
		//创建球体
		private function creatBalls(num:int):void
		{
			for (var i:int=0; i<num; i++)
			{
				var ball:Ball=new Ball(Math.random()*30+10,0xffffff *Math.random());
				ball.x=Math.random()*500;
				ball.y=0;
				ball.vy=Math.random()*10;//不同的初速度
				contain.addChild(ball);
				list.push(ball);
			}
		}
		private function Run(event:Event):void
		{

			for (var i:int=0; i<list.length; i++)
			{
				list[i].vy+=g;//加速度加上向下的垂直速度
				list[i].vy*=friction;//阻力
				list[i].y+=list[i].vy;// s=vt;
				if (list[i].y+list[i].height/2>stage.stageHeight)
				{
					list[i].y=stage.stageHeight-list[i].height/2;
					list[i].vy*=-1;
				}
			}
		}
	}
}

import flash.display.Sprite;
class Ball extends Sprite
{
	public var vy:Number=0;
	public var vx:Number=0;
	function Ball(r:int,color:uint)
	{
		this.graphics.lineStyle(1);
		this.graphics.beginFill(color);
		this.graphics.drawCircle(0,0,r);
		this.graphics.endFill();
		this.x=-this.width/2;
		this.y=-this.height/2;
	}
}

import flash.display.Sprite;
import flash.text.TextField;
//按钮
class MyButton extends Sprite
{
	function MyButton()
	{
		this.graphics.lineStyle(1);
		this.graphics.beginFill(0xffff00);
		this.graphics.drawRect(0,0,60,20);
		this.graphics.endFill();
		var txt:TextField=new TextField();
		txt.text="RePlay";
		txt.x=10;
		txt.y=2; 
		txt.mouseEnabled=false;
		addChild(txt);
	}
}

Forked