AS3版本的Flash弹性原型

今天,我把一个旧的教程(如何在弹力游戏中控制小球类物体)用AS3来实现。
我做这个教程,是因为在我心目中,这是一个很牛的游戏,它在Box2D已经推出的情况下,使用“非Box2D技术”并且还有市场。
关于全部的理论与物件的使用,可以参考原来的帖子,这里只介绍开始部分。
废话不说,让我们先来看看代码吧…这里有5个原型类:

main class

这是主类,调用其他分类


package {
	import flash.display.Sprite;
	import flash.ui.Mouse
	public class main extends Sprite {
		public var circle:circle_mc = new circle_mc();
		public var crosshair:crosshair_mc = new crosshair_mc();
		public var newmouse:newmouse_mc = new newmouse_mc();
		public var ball:ball_mc = new ball_mc();
		public function main():void {
			Mouse.hide();
			addChild(circle);
			addChild(crosshair);
			addChild(newmouse);
			addChild(ball);
		}
	}
}

circle_mc class

这是你可以移动里面准星的那个大圈圈的类

package {
	import flash.display.Sprite;
	public class circle_mc extends Sprite {
		public function circle_mc():void {
			x = 250;
			y = 200;
		}
	}
}

我只是简单的把它放在舞台中央

newmouse_mc class

这是鼠标的替代品

package {
	import flash.display.Sprite;
	import flash.events.Event;
	public class newmouse_mc extends Sprite {
		public function newmouse_mc():void {
			addEventListener(Event.ENTER_FRAME,on_enter_frame);
		}
		public function on_enter_frame(e:Event):void {
			x=stage.mouseX;
			y=stage.mouseY;
		}
	}
}

它只是跟随目标而已…

crosshair_mc class

准星跟随鼠标但不能进入大圈圈内

package {
	import flash.display.Sprite;
	import flash.events.Event;
	public class crosshair_mc extends Sprite {
		public function crosshair_mc():void {
			addEventListener(Event.ENTER_FRAME,on_enter_frame);
		}
		public function on_enter_frame(e:Event):void {
			var par:main=this.parent as main;
			var circle_limit:Number = par.circle.width/2-width/2
			x=stage.mouseX;
			y=stage.mouseY;
			var dist_x:Number=x-par.circle.x;
			var dist_y:Number=y-par.circle.y;
			var distance:Number=dist_x*dist_x+dist_y*dist_y;
			if (distance>circle_limit*circle_limit) {
				var angle:Number=Math.atan2(dist_y,dist_x);
				x=250+circle_limit*Math.cos(angle);
				y=200+circle_limit*Math.sin(angle);
			}
		}
	}
}

ball_mc class

最后,小球跟随准星并且有弹性效果

package {
	import flash.display.Sprite;
	import flash.events.Event;
	public class ball_mc extends Sprite {
		public var friction:Number=0.9;
		public var speed_scale:Number=0.1;
		public var xspeed:Number=0;
		public var yspeed:Number=0;
		public function ball_mc():void {
			addEventListener(Event.ENTER_FRAME,on_enter_frame);
			addEventListener(Event.ADDED_TO_STAGE,on_added_stage);
		}
		public function on_enter_frame(e:Event):void {
			var par:main=this.parent as main;
			var dist_x:Number = (par.crosshair.x-x)*speed_scale;
			var dist_y:Number = (par.crosshair.y-y)speed_scale;
			xspeed+=dist_x;
			yspeed+=dist_y;
			xspeed=friction;
			yspeed*=friction;
			x+=xspeed;
			y+=yspeed;
		}
		public function on_added_stage(e:Event):void {
			var par:main=this.parent as main;
			x=par.circle.x;
			y=par.circle.y;
		}
	}
}

这就是成果啦:


这里有几种方法可以使用这些原型…我将在接下来的几天展示如何在Box2D世界中整合它们。

源码可以在这里下载:

Download the source code.