Skip navigation
Currently Being Moderated

Code Question

Apr 20, 2012 5:21 AM

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;

            }

        }

    }

   

   

}

 
Replies
  • Currently Being Moderated
    Apr 20, 2012 5:56 AM   in reply to Winston2

    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;

                }

     
    |
    Mark as:

More Like This

  • Retrieving data ...

Bookmarked By (0)

Answers + Points = Status

  • 10 points awarded for Correct Answers
  • 5 points awarded for Helpful Answers
  • 10,000+ points
  • 1,001-10,000 points
  • 501-1,000 points
  • 5-500 points