• Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
    Dedicated community for Japanese speakers
  • 한국 커뮤니티
    Dedicated community for Korean speakers
Exit
0

Code Question

Explorer ,
Apr 20, 2012 Apr 20, 2012

Copy link to clipboard

Copied

Hi, I'm using Flash CS5 and actionscript 3 and going through a "bouncing ball" tutorial from a book that I bought.

The ball is supposed to bounce around a window indefinately.

The example works but instead of the ball keeping within the boundaries of the window it floats off the screen never to return.

Can someone please have a look at the code below and tell me what I can add to make this work as described?

Thank you very much.

package {

    //Import necessary classes

    import flash.display.MovieClip;

    import flash.events.Event;

    import flash.geom.ColorTransform;

    import flash.geom.Rectangle;

   

    public class Ball extends MovieClip {

        //Horizontal speed and direction

        public var speedX:int = 10;

       

        //Vertical speed and direction

        public var speedY:int = -10;

       

        //Constructor

        public function Ball() {

            addEventListener(Event.ENTER_FRAME, onEnterFrame);

            //Colors the ball a random color

            var colorTransform:ColorTransform = new ColorTransform();

            colorTransform.color = Math.random()*0xffffff;

            transform.colorTransform = colorTransform;

        }

       

        //called every frame

        private function onEnterFrame(event:Event):void{

            //Move ball by appropriate amount

            x += speedX;

            y += speedY;

           

            //Get boundary

            var bounds:Rectangle = getBounds(parent);

           

            //Reverse

            //of stage.

            if (bounds.left < 0 || bounds.right > stage.stageWidth) {

                speedX *= -1;

            }

        }

    }

   

   

}

TOPICS
ActionScript

Views

409

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
Apr 20, 2012 Apr 20, 2012

Copy link to clipboard

Copied

LATEST

It looks like you do not have anything to keep the ball within the boundaries for the y side of the story, only the x.  You need to have something for speedY just like you do for speedX where you check the bounds.top and bounds.bottom...

            if (bounds.top < 0 || bounds.bottom > stage.stageHeight) {

                speedY *= -1;

            }

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines