您的位置:首页 > 编程语言

【AS3代码】滚动的小球

2012-04-19 16:03 176 查看
文档类

package

{
import com.Boll;

import flash.display.Sprite;
import flash.display.StageScaleMode;
import flash.events.Event;

public class Main extends Sprite
{
//小球的范围内上下左右的极限边界值
private var left:uint = 43;
private var right:uint = 457;
private var top:uint = 43;
private var bottom:uint = 247;

public function Main():void
{
//舞台设为无缩放模式
stage.scaleMode = StageScaleMode.NO_SCALE;
init();

//5个黑色小球与5个白色小球绑定在一起
addEventListener(Event.ENTER_FRAME, bdong);
}

private function init():void
{
//生成5个黑色小球
for(var i:uint = 0; i<5; i++)
{
var blackball:Boll = new Boll(0x000000, 43);
this.addChildAt(blackball, i); //将小球添加到舞台(带上深度位置)
}

//生成5个白色小球(半径小于黑色球)
for(var t:uint = 0; t<5; t++)
{
var wball:Boll = new Boll(0xffffff, 40);
wball.x = 55 * (t+1); //小球横向定位
wball.y = 140; //小球纵向定位
wball.xspeed = Math.random() * 5 + 1; //横向移动速度(在1-6间随机)
wball.yspeed = t + 5; //纵向移动速度
this.addChildAt(wball, t+5); //白色小球深度之所以+5,是因为之前还有5个深度范围在0-4黑色小球

//白色小球运动的事件
wball.addEventListener(Event.ENTER_FRAME, wdong);

//白色小球附带黑色小球运动的事件
}
}
//白色小球运动的事件
private function wdong(evt:Event):void
{
evt.target.x += evt.target.xspeed; //小球每次横向运动的运动量
evt.target.y += evt.target.yspeed; //小球每次纵向运动的运动量

//如果小球碰到了边界时,反向运动
if(evt.target.x <= left || evt.target.x >= right)
{
evt.target.xspeed *= -1;

}
if(evt.target.y <= top || evt.target.y >= bottom)
{
evt.target.yspeed *= -1;
}
}
//5个黑色小球与5个白色小球绑定在一起
private function bdong(evt:Event):void
{
for(var h:int = 0; h < 5; h++)
{
getChildAt(h).x = getChildAt(h+5).x;
getChildAt(h).y = getChildAt(h+5).y;
}
}
}
}

生成小球类

package com
{
//x轴越大,向右运动。y轴越大,向下运动。
import flash.display.Shape;
public class Boll extends Shape
{
private var _xspeed:int; //小球横向运动变化量
private var _yspeed:int; //小球纵向运动变化量

//_color颜色,_r小球半径
public function Boll(_color:uint, _r:uint)
{
init(_color, _r);
}
private function init(_color:uint, _r:uint):void
{
//创建小球
this.graphics.beginFill(_color);
this.graphics.drawCircle(0,0,_r);
this.graphics.endFill();
}

public function get xspeed():int
{
return _xspeed;
}
public function set xspeed(n:int):void
{
_xspeed = n;
}
public function get yspeed():int
{
return _yspeed;
}
public function set yspeed(n:int):void
{
_yspeed = n;
}
}}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: