拖动和运动模拟
1.构建小球精灵
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
package
{
import flash.display.Sprite;
public class Ball extends Sprite
{
public var radius:Number;
public var color:uint;
public function Ball (radius:Number,color:uint)
{
this.radius=radius;
this.color=color;
Init ();
}
public function Init ():void
{
graphics.beginFill (color);
graphics.drawCircle (0,0,radius);
graphics.endFill ();
}
}
}
2.构建拖动和运动动画
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
package
{
import flash.display.Sprite;
import flash.display.StageScaleMode;
import flash.display.StageAlign;
import flash.events.MouseEvent;
import flash.events.Event;
public class DragAndMove extends Sprite
{
private var ball:Ball;
private var vx:Number;
private var vy:Number;
private var bounce:Number=-0.8;
private var gravity:Number=0.9;
public function DragAndMove ()
{
Init ();
}
public function Init ():void
{
stage.scaleMode=StageScaleMode.NO_SCALE;
stage.align=StageAlign.TOP_LEFT;
ball=new Ball(20,0xFFF000);
ball.x=stage.stageWidth/2;
ball.y=stage.stageHeight/2;
vx=Math.random()*20-10;
vy=-20;
addChild (ball);
ball.addEventListener (MouseEvent.MOUSE_DOWN,MouseDown);
addEventListener (Event.ENTER_FRAME,EnterFrame);
}
private function EnterFrame (e:Event):void
{
vy+=gravity;
ball.x+=vx;
ball.y+=vy;
if (ball.x<ball.radius)
{
ball.x=ball.radius;
vx*=bounce;
}
else if (ball.x+ball.radius>stage.stageWidth)
{
ball.x=stage.stageWidth-ball.radius;
vx*=bounce;
}
if (ball.y<ball.radius)
{
ball.y=ball.radius;
vy*=bounce;
}
else if (ball.y+ball.radius>stage.stageHeight)
{
ball.y=stage.stageHeight-ball.radius;
vy*=bounce;
}
}
private function MouseDown (e:MouseEvent):void
{
stage.addEventListener (MouseEvent.MOUSE_UP,MouseUp);
ball.startDrag ();
removeEventListener (Event.ENTER_FRAME,EnterFrame);
}
private function MouseUp (e:MouseEvent):void
{
stage.removeEventListener (MouseEvent.MOUSE_UP,MouseUp);
ball.stopDrag ();
addEventListener (Event.ENTER_FRAME,EnterFrame);
}
}
}