How can I spawn butterflies?


(Nate ) #1

Another related question! So I just finished making a cute little butterfly to add to the scenery of my level, and I would like him to spawn with a random X and Y value and flutter left and right randomly… this is the code I have in his update function, currently what happens is he like spazzes out to the left then right on off on off non stop… lol Any thoughts?

			if (FP.rand(2) > 0)
			{
			x -= power;
			sprButterfly.play("fly");
			}
			else
			{
			x += power;
			sprButterfly.play("fly_right");
			}

Simple Boolean Question.. not for me though
(David Williams) #2

For the butterfly, this is happening every frame, so 60x a second. You can get around this by using a timer: Create a private variable to hold the time:

private var timer:Number = 0;

Then, increment it using FP.elapsed (The amount of time that has passed since the last frame).

        timer += FP.elapsed;
        if (timer >= 2) //2 seconds!
        {
            if(FP.rand(2) > 0)
            {
                x -= power;
                sprButterfly.play("fly");
            }
            else
           {
                x += power;
                sprButterfly.play("fly_right");
           }
           timer -= 2; //Remove the amount that it was checking for from it (2 seconds)
        }

(David Williams) #3

Check if by moving by the power it will be off the screen before moving:

        if(FP.rand(2) > 0)
        {
            if(x - power >= 0)
            {
                x -= power;
                sprButterfly.play("fly");
            }
        }
        else
       {
            if(x + power <= 640)
            {
                x += power;
                sprButterfly.play("fly_right");
            }
       }

(Nate ) #4

Okay I got it, my butterfly now moves left and right randomly and will not leave the level!