ホームに戻る
ActionScript3.0 円を動かす
// Main.as
package{
import flash.display.Sprite;
import flash.events.MouseEvent;
[SWF(width="300", height="200", backgroundColor="0xFFFFFF")]
public class Main extends Sprite
{
private const n:int = 50;
private var clicked_flag:int = -1;
private var c:Array;
public function Main()
{
c = new Array();
for(var i:int = 0; i < n; i++)
{
c[i] = new Circle1();
c[i].draw();
addChild(c[i]);
}
stage.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
stage.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
}
private function onMouseMove(event:MouseEvent):void
{
if(clicked_flag != -1)
{
c[clicked_flag].erace();
c[clicked_flag].setX(stage.mouseX);
c[clicked_flag].setY(stage.mouseY);
c[clicked_flag].draw();
}
}
private function onMouseDown(event:MouseEvent):void
{
for(var i:int = 0; i < n; i++){
if(c[i].hitTestPoint(stage.mouseX, stage.mouseY, true))
{
clicked_flag = i;
addChildAt(c[i], n-1);
}
}
}
private function onMouseUp(event:MouseEvent):void
{
clicked_flag = -1;
}
}
}
// Circle1.as
package
{
import flash.display.Shape;
import flash.display.Graphics;
public class Circle1 extends Shape
{
private const w:int = 300; // 画面の幅
private const h:int = 200; // 画面の高さ
private const r:int = 10; // 円の半径
private var px:int;
private var py:int;
private var g:Graphics;
public function Circle1()
{
this.px = getRandom(r, this.w - this.r - 1);
this.py = getRandom(r, this.h - this.r - 1);
this.g = this.graphics;
}
public function setX(px:int):void { this.px = px; }
public function setY(py:int):void { this.py = py; }
public function getX():int { return this.px; }
public function getY():int { return this.py; }
public function draw():void
{
g.lineStyle(1, 0x000000, 1.0); // 線の太さ、色、アルファ値
g.beginFill(0xFFFFFF, 1.0); // 面のスタイル設定
g.drawCircle(this.getX(), this.getY() , this.r);
g.endFill();
}
public function erace():void {
g.clear();
}
private function getRandom(nMin:int, nMax:int):int {
return Math.floor(Math.random() * (nMax-nMin + 1)) + nMin;
}
}
}