第五课 更复杂的动画:理解运动模型

课程内容:模仿物体自由落体运动,采用重力加速度模型计算物体位置

课程效果:小球从屏幕上方自由落体到下方

知识点

1. 创建重用的显示对象

2. 使用元数据控制舞台属性

3. 使用模型控制对象移动

4. 显示动态文本

主要步骤

1. 在FlashDevelop中创建Acceleration工程,类型为AS3 Project

2. 创建新类Ball

3. 代码如下

Main.as代码:

package

{

import flash.display.Sprite;

import flash.events.Event;

import flash.text.TextField;

/**

* ...

* @author happydagui

*/

[SWF(;400",height="300",frameRate="60")]

public class Main extends Sprite

{

private const gravity:Number = 9.80665;// 重力加速度

private var ball:Ball; // 小球

private var count:int; // 帧计数

private var secondText:TextField; // 显示经过的时间(秒)

public function Main():void

{

if (stage) init();

else addEventListener(Event.ADDED_TO_STAGE, init);

}

private function init(e:Event = null):void

{

removeEventListener(Event.ADDED_TO_STAGE, init);

// entry point

ball = new Ball();

ball.x = 100;

addChild(ball);

secondText = new TextField();

secondText.text = "0";

addChild(secondText);

addEventListener(Event.ENTER_FRAME, myEnterFrame);

}

public function myEnterFrame(event:Event):void

{

count++;

if (count % stage.frameRate == 0)

{

secondText.text = (count / stage.frameRate).toString();

}

// 按照每秒stage.frameRate帧播放flash,每播放一帧,相当于1/stage.frameRate秒

var t:Number = count / stage.frameRate;

// 计算重力加速度位移h=(g*t^2)/2

ball.y = gravity * t * t / 2;

trace(ball.y);

if (ball.y > stage.stageHeight) {

ball.y = 0;

count = 0;

}

}

}

}

Ball.as代码

package

{

import flash.display.Sprite;

/**

* ...

* @author happydagui

*/

public class Ball extends Sprite

{

public function Ball()

{

init();

}

public function init():void

{

graphics.lineStyle(1, 0xff0000);

graphics.beginFill(0x00ff00);

graphics.drawCircle(1, 1, 2);

graphics.endFill();

}

}

}

你可能感兴趣的:(知识点,模型,运动,加速度,自由落体)