2006/04/30 | AS 控制小球弹跳
类别(Flash课件设计) | 评论(5) | 阅读(428) | 发表于 23:36
前些天,准备一个短篇的讲稿时想了一个小球弹跳的例子,当时实现了基本的运动,在准备实现重力效果里却出了问题,今天收到另一个例子,恰好解决了这样的问题,合并起来算是一个完整的实例了.

AS 控制小球弹跳

_root 中写入

var top = 100;
var bottom = 300;

//实现小球的单向运动.

ball.onterFrame = function() {
this._y += 20;
if( this._y > _root.bottom ) {
this._y = _root.top;
}
}

改进一:
//实现小球的双向运动.
_root 中加入
var ymov = 20;

ball.onterFrame = function() {
this._y += _root.ymov;
if( this._y > _root.bottom ) {
_root.ymov = -20;
}
if( this._y < _root.top ) {
_root.ymov = 20;
}
}

改进二:
//双向运动的代码优化.

ball.onterFrame = function() {
this._y += _root.ymov;
if( this._y > _root.bottom || this._y < _root.top) {
_root.ymov = -_root.ymov;
}
}

改进三:
//加入重力因素.

yspeed = 0;
gravity = 2.400000;
friction = 1; //运动时的速度损耗系数,为 1 时没有损耗.
bounce = 0.9; //反弹时的速度损耗系数,为 1 时没有损耗.
forceDribble =22;
bottom = 300;

ball.onEnterFrame = function ()
{
this._y = this._y + yspeed;
if (this._y > bottom)
{
yspeed = -yspeed * bounce;
this._y = bottom; //确保速度的反转只进行一次.
} // end if
yspeed = yspeed * friction + gravity;
//在速度中加入损耗系数和重力加速度.
};

最后再列出一个完整的、复杂的运动效果的应用,点击小球,小球将被抛起,不点击时,小球自由下落。

_root.createEmptyMovieClip("ball", 69);
ball.lineStyle(60, 16777215, 100);
ball.lineTo(1, 0);
vars = new Array("xspeed", "yspeed", "leftedge", "rightedge", "bottomedge", "gravity", "friction", "bounce", "widthBall", "heightBall", "maxaffiche", "forceDribble", 6, 0, -30, Stage.width + _root.ball._width / 4, Stage.height + _root.ball._width / 4, 2.400000, 0.982000, 0.700000, _root.ball._width / 2, _root.ball._height / 2, 10, 22);
for (i = 0; i < vars.length / 2; i++)
{
this[vars[i]] = vars[i + vars.length / 2];
} // end of for
ball.onPress = function ()
{
var _l1 = _root;
_l1.xspeed = _l1.xspeed - (_l1._xmouse - this._x) / 2;
_l1.yspeed = -_l1.forceDribble;
};
ball.onEnterFrame = function ()
{
var _l1 = this;
_l1._x = _l1._x + xspeed;
_l1._y = _l1._y + yspeed;
if (_l1._x + widthBall > rightedge || _l1._x - widthBall < leftedge)
{
xspeed = -xspeed * bounce;
_l1._x = _l1._x + widthBall > rightedge ? (rightedge - widthBall) : (leftedge + widthBall);
} // end if
if (_l1._y + heightBall > bottomedge)
{
yspeed = -yspeed * bounce;
_l1._y = bottomedge - heightBall;
} // end if
yspeed = yspeed * friction + gravity;
xspeed = xspeed * friction;
};
效果如下所示:

Flash 动画
0

评论Comments