Ex05_ex2

by shuto.suzuki
♥0 | Line 51 | Modified 2011-06-27 15:38:19 | MIT License
play

ActionScript3 source code

/**
 * Copyright shuto.suzuki ( http://wonderfl.net/user/shuto.suzuki )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/bB81
 */

package
{
    import flash.display.Sprite;
    import flash.display.StageAlign;
    import flash.display.StageScaleMode;
    import flash.events.Event;
    
    [SWF(backgroundColor = "0x000000", width = 256, height = 256)]
    
    public class Ex05_ex2 extends Sprite
    {
        // 円を移動させる変数ballの宣言。
        private var ball:Sprite;
        // ボールの半径rの宣言。
        private var r:Number = 20;
        // ボールの縦方向の移動量vyの宣言。
        private var vy:Number = 5;
        
        private var vx:Number = 5;
        
        private var g:Number = 0.98;
        
        public function Ex05_ex2()
        {
            stage.scaleMode = StageScaleMode.NO_SCALE;
            stage.align = StageAlign.TOP_LEFT;
            
            // ballの初期化
            ball = new Sprite();
            
            //座標(0, 0)に半径50の赤い円を作る
            ball.graphics.beginFill(0xff0000);
            ball.graphics.drawCircle(0, 0, r);
            ball.graphics.endFill();
            
            // ballの位置を画面の真ん中に置く
            ball.x = stage.stageWidth / 2;
            ball.y = 100;
            
            // ボールを画面に追加する。
            addChild(ball);
            
            // フレームごとのイベントを追加する。
            addEventListener(Event.ENTER_FRAME, onEnterFrame);
        }
        
        // ボールを弾ませるイベント関数onEnterFrame
        private function onEnterFrame(e:Event):void
        {
            ball.y += vy;
            ball.x += vx;            
            // 画面領域からはみ出した場合は、移動方向を反転させる。
            // 反転の仕方は次の2通り。
            // <その1>
            //   vx(vy)をマイナスにする
            //     (例)vx = -vx;
            // <その2>
            //   vx(vy)にマイナスをかけてやる
            //    (例)vy *= -1; ←この数字の1は反発係数なのでこの部分を変えると弾み方が変わる
            // 下にある解答は<その2>を使ってます。
            // <その1>でも同じように動作するか確かめてみてください。
            
            // y方向の壁衝突の処理
            if(stage.stageHeight < ball.y + r){
                // 正の方向にはみ出した場合の処理
                vy *= -1;
                ball.y = stage.stageHeight - r;
            }
            if(stage.stageWidth < ball.x + r){
                vx *= -1;
                ball.x = stage.stageWidth - r;
            }
            if(0 > ball.y - r){
                vy *= -1;
                ball.y = r;
            }
            if(0 > ball.x - r){
                vx *= -1;
                ball.x = r;
            }
        vy += g;
        }
    }    
}