- 2009-12-11 (金) 11:10
- ActionScript 3.0 作業メモ
ランダムにボールの色を変えてみる『Math.random() * 0xffffff』
ランダムにボールの色を変える前に、準備としてBallクラス(Ball.as)を作成しといて外部ファイルから読み込んでボールを作ります。
※Ball.asを使いたいファイルと同階層に配置してください。
package {
//インポート
import flash.display.Sprite;
//コンスラクタ
public class Ball extends Sprite{
//インスタンスプロパティー
public var radius:Number;
public var color:uint;
//メソッドメニュー
public function Ball(radius:Number, color:uint) {
this.radius = radius;
this.color = color;
init();
}
//メソッド
public function init():void{
graphics.beginFill(color);
graphics.drawCircle(0, 0, radius);
graphics.endFill();
}
}
}
radius(ボールのサイズ)とcolor(ボールの色)をあらかじめ変数に置き換えて、Ball.asを読み込んでボールを作る時に指定します。
表示させていファイルにNew演算子を使ってボールを作ります。この時にサイズと色を指定します。
今回はサイズ50と色を取り合えず青にします。
//Ball.asを読み込み var ball:Ball = new Ball(50, 0x0000ff); addChild(ball); ball.x = stage.stageWidth / 2; ball.y = stage.stageHeight / 2;
これでパブリッシュするとステージの真ん中に青のボールが表示されると思います。
では、次に色をランダムにします。
ランダムにするには、Math.random()を使うので、これを利用して、『Math.random() * 0xffffff』とします。
これで色がランダムに変わります。
//Ball.asを読み込み var ball:Ball = new Ball(50, Math.random() * 0xffffff); addChild(ball); ball.x = stage.stageWidth / 2; ball.y = stage.stageHeight / 2;
上記はランダムを取り入れた、完成版です。
再読み込みすればボールの色が変わります。
日本の国旗になった人はすごいラッキーな人です。
Comments:0
Trackbacks:0
- Trackback URL for this entry
- http://www.addchild.net/as3-memo/352.html/trackback
- Listed below are links to weblogs that reference
- Math.random() を使ってランダムに色を変える方法 from ADD CHILD = AS3