1 Reply Latest reply: Apr 20, 2012 5:56 AM by Ned Murphy RSS

    Code Question

    Winston2

      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;

                  }

              }

          }

         

         

      }

        • 1. Re: Code Question
          Ned Murphy MVP

          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;

                      }