开发者

Animated MovieClip jumps around screen randomly

开发者 https://www.devze.com 2023-01-26 01:57 出处:网络
I have an animated MovieClip of a fly that spawns at a random location and moves across the screen by bouncing off the walls. But every time the animation starts over, it seems to \"jump\" to a random

I have an animated MovieClip of a fly that spawns at a random location and moves across the screen by bouncing off the walls. But every time the animation starts over, it seems to "jump" to a random location. Here is the code I have for when it spawns:

private function beginClass(e:Event):void{
   _root = MovieClip(root);

   do { 
    xRandom = Math.floor(Math.random() * 500); 
    yRandom = Math.floor(Math.random(开发者_运维百科) * 350); 
    this.x = xRandom;
    this.y = yRandom;
    } while (Math.abs(xRandom - mouseX) > 20 && Math.abs(yRandom - mouseY) > 20);

  }

And this is the code for its movement:

//Bouncing the fly off of the walls
   if(this.x >= stage.stageWidth-this.width){
   //if the fly hits the right side
   //of the screen, then bounce off
   flyXSpeed *= -1;
   }
   if(this.x <= 0){
   //if the fly hits the left side
   //of the screen, then bounce off
   flyXSpeed *= -1;
   }
   if(this.y >= stage.stageHeight-this.height){
   //if the fly hits the bottom
   //then bounce up
   flyYSpeed *= -1;
   }
   if(this.y <= 0){
   //if the fly hits the top
   //then bounce down
   flyYSpeed *= -1;

}

How do I fix it so that the fly continues moving in its appropriate path every time the animation starts over?


If I understand the problem correctly, when starting the animation you have to check if it has already been started before.

A simple boolean variable would do:

private var hasStarted:Boolean = false;    

private function beginClass(e:Event):void{
   _root = MovieClip(root);

   if (!hasStarted) {
       hasStarted = true;

       do { 
           xRandom = Math.floor(Math.random() * 500); 
           yRandom = Math.floor(Math.random() * 350); 
           this.x = xRandom;
           this.y = yRandom;
       } while (Math.abs(xRandom - mouseX) > 20 && Math.abs(yRandom - mouseY) > 20);
   }
}

This way it'll only execute the random placing code once.

0

精彩评论

暂无评论...
验证码 换一张
取 消