forked from: Example for YAnswers

by bradsedito forked from Example for YAnswers (diff: 1)
♥0 | Line 35 | Modified 2012-06-11 23:48:42 | MIT License
play

ActionScript3 source code

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

// forked from antalg's Example for YAnswers
package {
    import flash.text.TextField;
    import flash.events.MouseEvent;
    import flash.events.Event;
    import flash.display.Sprite;
    
    [SWF(backgroundColor = 0xCCCCCC, frameRate = 40)]
    
    public class FlashTest extends Sprite {
        public function FlashTest() {
            var t:TextField = new TextField();
            addChild(t);
            
            var ball_mc:Sprite = new Sprite(); 
            
            var r:int = 15;
            ball_mc.graphics.beginFill(0x555555);
            ball_mc.graphics.drawCircle(-r,-r,r);
            ball_mc.graphics.endFill();
            // A new sprite with bottom right reg.point
            
            ball_mc.x = 175;
            ball_mc.y = 230;
            
            addChild(ball_mc);
            
            // Relevant code below //
            ball_mc.addEventListener(Event.ENTER_FRAME, moveBall);
            var pxX:Number = 17;    // define variables with a base value
            var pxY:Number = 17;    // these variables will keep their values between each function call
            
            function moveBall(event:Event):void {
                
                // If past right edge OR past left edge, reverse x direction (|| means or)
                if(ball_mc.x >= stage.stageWidth || ball_mc.x <= ball_mc.width){
                    pxX*=-1;
                }
                
                // If past bottom edge OR past top edge, reverse y direction (|| means or)
                if(ball_mc.y >= stage.stageHeight || ball_mc.y <= ball_mc.height){
                    pxY *= -1;
                }
                
                /*
                    The reason to use: "*= -1" is to make the code more dynamic.
                    If you would want to change the speed of the ball, the only thing
                    that needs to be changed is the initial values of pxX and pxY.
                */
                
                ball_mc.x += pxX;
                ball_mc.y += pxY;
                
                t.text = "["+pxX+","+pxY+"] ["+ball_mc.x+","+ball_mc.y+"]";    // Just for debugging
            }
        }
    }
}