SPRING PARTICLES
Main
メインクラス.
/**
* Copyright kazy ( http://wonderfl.net/user/kazy )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/oNX4
*/
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.geom.Point;
/**
* Main
* メインクラス.
*/
public class Main extends Sprite
{
private var particles:Array;
private var numParticles:uint = 100;
private var minDist:Number = 100;
private var springAmount:Number = .001;
/**
* コンストラクタ.
*/
public function Main()
{
init();
}
/**
* 初期設定.
*/
private function init():void
{
particles = new Array();
//numParticlesの数だけボール生成
for(var i:uint = 0; i < numParticles; i++)
{
var particle:Ball = new Ball(2);
particle.x = Math.random() * stage.stageWidth;
particle.y = Math.random() * stage.stageHeight;
particle.vx = Math.random() * 6 - 3;
particle.vy = Math.random() * 6 - 3;
addChild(particle);
particles.push(particle);
}
//ENTER_FRAMEをリスナー登録
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
/**
* onEnterFrame.
*/
private function onEnterFrame(event:Event):void
{
for(var i:uint = 0; i < numParticles; i++)
{
var particle:Ball = particles[i];
//加速
particle.x += particle.vx;
particle.y += particle.vy;
//ステージを出たら、反対側から入る
if(particle.x > stage.stageWidth)
{
particle.x = 0;
}
else if(particle.x < 0)
{
particle.x = stage.stageWidth;
}
if(particle.y > stage.stageHeight)
{
particle.y = 0;
}
else if(particle.y < 0)
{
particle.y = stage.stageHeight;
}
}
for(i=0; i < numParticles - 1; i++)
{
var partA:Ball = particles[i];
for(var j:uint = i + 1; j < numParticles; j++)
{
var partB:Ball = particles[j];
//バネの動き
spring(partA, partB);
}
}
}
/**
* ボール間スプリング.
* @param partA ボールA
* @param partB ボールB
*/
private function spring(partA:Ball, partB:Ball):void
{
//各座標の距離
var dx:Number = partB.x - partA.x;
var dy:Number = partB.y - partA.y;
//直線距離
var dist:Number = Math.sqrt(dx * dx + dy * dy);
if(dist < minDist)
{
//スプリング加速
var ax:Number = dx * springAmount;
var ay:Number = dy * springAmount;
//各ボールの加速度へ設定
partA.vx += ax;
partA.vy += ay;
partB.vx -= ax;
partB.vy -= ay;
}
}
}
}
/**
* Ball
* ボール生成クラス.
*/
class Ball extends flash.display.Sprite {
public var radius:Number;
private var color:uint;
public var vx:Number = 0;
public var vy:Number = 0;
public var mass:Number = 1;
/**
* コンストラクタ.
*/
public function Ball(radius:Number=40, color:uint=0x990033) {
this.radius = radius;
this.color = color;
init();
}
/**
* 初期化.
*/
public function init():void {
graphics.beginFill(color);
graphics.drawCircle(0, 0, radius);
graphics.endFill();
}
}