flash on 2009-12-30
/**
* Copyright h_ike ( http://wonderfl.net/user/h_ike )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/bMOJ
*/
package {
import flash.display.Sprite;
import flash.events.*;
[SWF (backgroundColor="0x000000")]
public class FlashTest extends Sprite {
private var balls:Array;
private var ball:Ball;
private var numBalls:Number = 20;
private var bounce:Number = -0.2;
private var spring:Number = 0.9;
private var gravity:Number = 0;
public function FlashTest() {
balls = new Array();
for(var i:uint=0;i<numBalls;i++){
var ball:Ball = new Ball(8,Math.random()*0xffffff);
ball.x = Math.random()*stage.stageWidth;
ball.y = Math.random()*stage.stageHeight;
ball.vx = Math.random()*6 - 3;
ball.vy = Math.random()*6 - 3;
addChild(ball);
balls.push(ball);
}
addEventListener(Event.ENTER_FRAME,loop);
}
private function loop(e:Event):void{
for(var i:uint=0;i<numBalls - 1;i++){
var ball0:Ball = balls[i];
for(var j:uint=i+1;j<numBalls;j++){
var ball1:Ball = balls[j];
var dx:Number = ball1.x - ball0.x;
var dy:Number = ball1.y - ball0.y;
var dist:Number = Math.sqrt(dx*dx + dy*dy);
var minDist:Number = ball0.radius + ball1.radius;
if(dist<minDist){
var angle:Number = Math.atan2(dy,dx);
var tx:Number = ball0.x + Math.cos(angle)*minDist;
var ty:Number = ball0.y + Math.sin(angle)*minDist;
var ax:Number = (tx - ball1.x)*spring;
var ay:Number = (ty - ball1.y)*spring;
ball0.vx -= ax;
ball0.vy -= ay;
ball1.vx += ax;
ball1.vy += ay;
}
}
}
for(i=0;i < numBalls;i++){
var ball:Ball = balls[i];
ball.vy += gravity;
ball.x += ball.vx;
ball.y += ball.vy;
if(ball.x + ball.radius > 465){
ball.x = 465 - ball.radius;
ball.vx *= bounce;
}else if(ball.x - ball.radius < 0){
ball.x = ball.radius;
ball.vx *= bounce;
}
if(ball.y + ball.radius > 465){
ball.y = 465 - ball.radius;
ball.vy *= bounce;
}else if(ball.y - ball.radius < 0){
ball.y = ball.radius;
ball.vy *= bounce;
}
}
}
}
}
import flash.display.*;
class Ball extends Sprite{
public var radius:Number;
private var color:uint;
public var vx:Number = 0;
public var vy:Number = 0;
public function Ball(radius:Number=40,color:uint=0xff0000){
this.radius = radius;
this.color = color;
this.vx=0;
this.vy=0;
this.graphics.beginFill(color);
this.graphics.drawCircle(0,0,radius);
this.graphics.endFill();
}
}