# Flash AS3 - Random Button Linkage



## BadgerBoy (Feb 12, 2006)

I'm very new to Flash so I'm not sure what kind of info you need. I am working on a Mac with CS5.

So I have a flash file with 6 frames.

Each frame has a single button.

Each button is on its own layer.

What I want to have happen, is when the flash file is run, for a frame to pop up with a single button. 

When you click on the button, it will take you to a random frame, one of the 5 remaining frames.

This is the code I have so far:


stop ();

instanceNameForButton.addEventListener(MouseEvent.CLICK, gotoAndStopAnimation);
function gotoAndStopAnimation(event:MouseEvent):void
{
function randRange(min, max){
var randomNum= Math.floor(Math.random()*(max-min+1))+min;
return randomNum;
}
var say;
say = randRange(1,6);
gotoAndStop(say);

} 

It doesn't seem to be working.

Anyone know what the correct code might be?


----------



## freddyhard (Jun 9, 2009)

here is the code i'd use. i'm not great with AS3, but this works. i have attached the flash file for you to open as well. i did it with 5 frames, but the number of frames is irrelevant.

i only used 1 button, but you could call the same function from every button on what ever frame the movie is on. 


```
stop();
var RandomNumber:Number;
var No:Number;

Btn1.addEventListener(MouseEvent.CLICK, RandomFrame);


function RandomFrame(e:MouseEvent):void {
	RandomNumber = Math.random() * 5;
	No = Math.floor(RandomNumber) + 1;
	gotoAndStop(No);
}
```


----------



## BadgerBoy (Feb 12, 2006)

Thanks so very much!

It works great on the button for the first frame. 

So then I have buttons on each frame, which I then want each to go to a random frame when they're clicked on, just like the one on frame 1.

But when I put the code in the button on the second frame. I get several error codes.

They're all in regards to line 2, which reads: var RandomNumber:Number;

The error codes say the following:

Scene 1, Layer 'Button Instance Name', Frame 2, Line 2	1151: A conflict exists with definition RandomNumber in namespace internal.

Scene 1, Layer 'Button Instance Name', Frame 2, Line 3	1151: A conflict exists with definition No in namespace internal.

Scene 1, Layer 'Button Instance Name', Frame 2, Line 8	1021: Duplicate function definition.

Any ideas?

Thanks again!


----------



## freddyhard (Jun 9, 2009)

i added some text on each frame to display the frame number it is on. (see attached .fla file)
the code below is only on frame 1 and on each subsequent frame i only have the lower 2 lines, where Btn1 is changed for the button instance name on that frame. in my case Btn2, Btn3, Btn4, Btn5
the variables *No* & *RandomNumber* and the function *RandomFrame* have been declared on frame1. there is no need to declare them on any other frames

```
stop();
var RandomNumber:Number;
var No:Number = 1;

Btn1.addEventListener(MouseEvent.CLICK, RandomFrame);
Text.text = "Frame " + No;

function RandomFrame(e:MouseEvent):void {
	RandomNumber = Math.random() * 5;
	No = Math.floor(RandomNumber) + 1;
	gotoAndStop(No);
}
```


```
Btn1.addEventListener(MouseEvent.CLICK, RandomFrame);
Text.text = "Frame " + No;
```


----------



## BadgerBoy (Feb 12, 2006)

It works like a charm!

Thank you so very much!


----------



## BadgerBoy (Feb 12, 2006)

I have a few more questions if you're willing to help. I'm not sure where to start.

Basically with this project I want each frame to do the following three things:

1. I want there to be a sound file, the same sound file for each frame, that will be at maximum volume when the frame comes up, but as the mouse pointer gets closer to the button, I want the sound to fade until the pointer is directly over the button at which time it will get silent.

2. I want each frame to be completely black, and as the pointer gets closer to the button for the black layer to reduce in opacity until it's over the button at which time the layer will be completely transparent.

3. I want another image on each frame, a different image for each frame, to fade in from transparency when the mouse pointer is directly over the button.

Would you know how I might go about doing this in the way of AS3 code?


----------



## freddyhard (Jun 9, 2009)

it's been a while since i did anything in AS. do the buttons need to be invisible and randomly positioned on each frame?


----------



## BadgerBoy (Feb 12, 2006)

They do need to be invisible, but they're going to stick in the same place, they aren't going to be randomly positioned.


----------



## freddyhard (Jun 9, 2009)

this works. maybe it could have been written smarter.
what you need to do is save the 6 music files in the same directory as the flash file. they need to be named *song1.mp3* through to *song6.mp3* and should be mp3 encoded.
frame 1 i only used to set up these variables

```
var Music1:Sound = new Sound();                     // SETS UP 6 NEW SOUNDS
var Music2:Sound = new Sound();
var Music3:Sound = new Sound();
var Music4:Sound = new Sound();
var Music5:Sound = new Sound();
var Music6:Sound = new Sound();

var MusicCh1 = new SoundChannel();                  // SETS UP 6 CHANNELS TO PLAY/STOP SOUND
var MusicCh2 = new SoundChannel();
var MusicCh3 = new SoundChannel();
var MusicCh4 = new SoundChannel();
var MusicCh5 = new SoundChannel();
var MusicCh6 = new SoundChannel();

var MusicVolume = new SoundTransform();            // SOUNDTRANSFORM CLASS TO ALTER THE VOLUME


Music1.load(new URLRequest("song1.mp3"));          // LOADS THE 6 SOUNDS TO BE PLAYED ON EACH FRAME
Music2.load(new URLRequest("song2.mp3"));
Music3.load(new URLRequest("song3.mp3"));
Music4.load(new URLRequest("song4.mp3"));
Music5.load(new URLRequest("song5.mp3"));
Music6.load(new URLRequest("song6.mp3"));
```

practically all the code goes on frame2

```
stop();
var RandomNumber:Number;                                         // VARIABLES FOR
var FrameNo:uint;                                                // RANDOM NEXT FRAME

var Xvalue:Number;                                               // VARIABLES FOR CALULATING
var Yvalue:Number;                                               // DISTANCE MOUSE IS
var Distance:Number;                                             // FROM BUTTON

var FadeDistance:uint = 200;                                     // DISTANCE IN PIXELS TO START TO FADE BACKGROUND & VOLUME
                                                                 // CHNAGE HERE TO TWEAK



//+++++++++++++++++++++++++++++ ADD EVENTSLISTENERS +++++++++++++++++++++++++++++

Btn1.addEventListener(MouseEvent.CLICK, RandomFrame);            // JUMP TO NEXT FRAME FUCNTION
stage.addEventListener(Event.ENTER_FRAME, CalculateDistance);    // CALCULATE DISTANCE AT EVERY FRAME RATE
MusicCh1 = Music1.play();                                        // PLAY SOUND FOR THIS FRAME




//++++++++++++++++++++++++++++++++++ FUNCTIONS ++++++++++++++++++++++++++++++++++

function RandomFrame(event:MouseEvent):void {
	RandomNumber = Math.random() * 6;                            // GEMERATE RANDOM NUMBER BETWEEN 0 & 5.9999
	FrameNo = Math.floor(RandomNumber) + 2;                      // ROUND DOWN ADD 2 TO SKIP FRAME 1 & MAKE IT BETWEEN 2 & 7
	while ( FrameNo == currentFrame){                            // MAKE SURE IT JUMPS TO A DIFFERENT FRAME THAN CURRENT ONE
		RandomNumber = Math.random() * 6;
		FrameNo = Math.floor(RandomNumber) + 2;
	}
	MusicCh1.stop();                                             // STOP ALL MUSIC CHANNELS
	MusicCh2.stop();                                             // SO IT WILL STOP
	MusicCh3.stop();                                             // WHICHEVER ONE IS PLAYING
	MusicCh4.stop();
	MusicCh5.stop();
	MusicCh6.stop();
	gotoAndStop(FrameNo);                                        // JUMP TO RANDOM FRAME
}


function CalculateDistance(event:Event):void {
	Xvalue = (mouseX - Btn1.x) * (mouseX - Btn1.x);              // USING PYTHAGORAS
	Yvalue = (mouseY - Btn1.y) * (mouseY - Btn1.y);              // TO MEASURE DISTANCE THE MOUSE IS FROM THE BUTTON
	Distance = Math.sqrt(Xvalue + Yvalue);
	BackGround_mc.alpha = Distance / FadeDistance;               // THIS WILL FADE THE BACKGROUND WHEN CLOSER THAN 200 PIXELS
	if ((Distance / FadeDistance) < 1){
		MusicVolume.volume = Distance / FadeDistance;            // WILL NOT LET THE VOLUME BECOME > 100% BUT
		MusicCh1.soundTransform = MusicVolume;                   // DECREASES
		MusicCh2.soundTransform = MusicVolume;                   // ALL
		MusicCh3.soundTransform = MusicVolume;                   // THE
		MusicCh4.soundTransform = MusicVolume;                   // MUSIC
		MusicCh5.soundTransform = MusicVolume;                   // CHANNELS
		MusicCh6.soundTransform = MusicVolume;                   // ONCE CLOSE ENOUGH
	}
}
```
with each of the last 5 frames getting one line, where 2 is incremented with each frame. this is to play that music file for that frame.

```
MusicCh2 = Music2.play();
[i]MusicCh3 = Music3.play();[/i]
[i]MusicCh4 = Music4.play();[/i]
[i]MusicCh5 = Music5.play();[/i]
[i]MusicCh6 = Music6.play();[/i]
```


----------



## BadgerBoy (Feb 12, 2006)

Thank you very much! I'll be working on it a bit more some time next week after the holiday, and let you know how it all worked out.

Thanks again!


----------



## BadgerBoy (Feb 12, 2006)

In regards to the sound, I'm getting the following error message:

Scene 1, Layer 'Scripts', Frame 2, Line 52	1151: A conflict exists with definition RandomNumber in namespace internal.

Frame 2, Line 52, says this:

var RandomNumber:Number; // VARIABLES FOR

Also, in the file you uploaded, there seems to be 7 frames as opposed to the 6 frames that I wanted to create. Am I reading that wrong?

Anyway, I've uploaded a copy of my flash file so you can see what is happening. Here's my file:

http://www.filedropper.com/religonexample

It was too large to attach directly to Tech Support Forums.com


----------



## BadgerBoy (Feb 12, 2006)

freddyhard said:


> i'm not having any luck with the sound varying in volume. i'll need to look a bit more into that. i did have the button being randomly positioned each time, but i deleted those 2 lines of code and put the button on each frame instead. see attached.
> 
> ```
> stop();
> ...


When I add this to the code on Frame, 1, it doesn't seem to be working and I get several error codes. Would you know what I did wrong here?

Here's my file so you can see if you'd like:

http://www.filedropper.com/religonexample2_1

Thanks again so much for your time!


----------



## freddyhard (Jun 9, 2009)

BadgerBoy said:


> In regards to the sound, I'm getting the following error message:
> 
> Scene 1, Layer 'Scripts', Frame 2, Line 52	1151: A conflict exists with definition RandomNumber in namespace internal.
> 
> ...


i'm not sure what you are doing with the code, because i am using CS3 and i can not open the files on the links you supplied. you would need to save them in that format for me to see what you are doing.

there are 7 frames, but the first one is only used to declare the variables and load the .mp3 files for the audio and is not called upon with the RandomFrames function. i suppose you don't have 6 audio tracks as *song1.mp3* through to *song6.mp3* in the same directory as the .fla file? because the code on frame 1 will try to load these files.

it is all in place with the .fla file i've attached on post #9. you can alter the stage size and move the buttons around on each frame as desired. you could then tweak the FadeDistance variable to how ever close you want the pointer to be to start to fade the background and music.


----------



## BadgerBoy (Feb 12, 2006)

That'a okay, the earliest I can save it as is CS4, as I'm working on CS5. I'm pretty dense with this stuff anyway. I'll keep trying to work on it and see if I can make some headway.

Thanks again so much for your help!


----------



## freddyhard (Jun 9, 2009)

the code/.fla file i've attached works as you described how you wanted it to behave. i'm not sure why you are altering it.


----------



## BadgerBoy (Feb 12, 2006)

I don't think I altered it, except where specific instance names made changing it necessary. 

Ultimately, I think it has more to do with me not really knowing what I'm doing.


----------



## freddyhard (Jun 9, 2009)

there are only 2 objects placed on the stage that have instantiated names;
the button *btn1* that when clicked goes to another frame
and the black rectangle *Background_mc* that was made into a movie clip so that i could alter it's alpha%
i can see no advantage to renaming these objects.
the audio files that you want to use for each frame should be renamed to song1 through to song6 and need to be .mp3 encoded.
alternatively you could rename the list of files to be loaded in frame 1 to match the ones save on the HD.
unless you have added objects to the stage there should be no problems with the code above. i have a friend that has CS5 installed, so i might try and get a look at your files tomorrow on that PC.


----------



## BadgerBoy (Feb 12, 2006)

If you get a chance, that would be wonderful. I have an updated file here any one of these sites:

http://www.filedropper.com/religonexample3

http://www.freefilehosting.net/religonexample3 

ReligonExample3.fla - download now for free. File sharing. Software file sharing. Free file hosting. File upload. FileFactory.com 

Thanks again for all your help!:beerchug:


----------



## freddyhard (Jun 9, 2009)

the religonexample3.fla seems to be corrupted. i get an unexpected file format when i try and open it. i tried it from 2 of those links.
however, i downloaded a trail version of flash CS5 and looked at the religonexample2. i used the images from that file to setup this one.
the only thing that is missing is an mp3 file to play. i misread your original request and i thought there was to be a different music file for each frame as to the same one.

if you want to omit music playing then blank out the last 5 lines of code on frame 1 and the 2 lines of code in the *RandomFrame* function that stops and starts the music. otherwise have an MP3 file (named "song1") in the same directory of the .fla file when you export it to test.
i think this is nearly finished?


----------



## freddyhard (Jun 9, 2009)

here is the code with the music lines blanked out. while there are 7 frames, the first frame is only used to set up some variables.
the *FadeDistance* variable should be tweaked to suit.

this link has the .fla file to download. the one in the above post was spelt wrong.

Frame1

```
var RandomNumber:Number;                            // VARIABLES FOR
var FrameNo:uint;                                   // RANDOM NEXT FRAME

var FirstJump:Boolean = true;                      // SET TO FALSE FOR FIRST TIME RANDOM JUMP

var Xvalue:Number;                                  // VARIABLES FOR CALULATING
var Yvalue:Number;                                  // DISTANCE MOUSE IS
var Distance:Number;                                // FROM BUTTON

var FadeDistance:uint = 150;                        // DISTANCE IN PIXELS TO START TRANSPARENCY. CHANGE HERE TO TWEAK

/*
var Music1:Sound = new Sound();                     // SETS UP SOUND
var MusicCh1 = new SoundChannel();                  // SETS UP CHANNEL TO PLAY/STOP SOUND
var MusicVolume = new SoundTransform();             // SOUNDTRANSFORM CLASS TO ALTER THE VOLUME


Music1.load(new URLRequest("song1.mp3"));           // LOADS THE SOUND TO BE PLAYED ON EACH FRAME
MusicCh1 = Music1.play();                           // PLAY SOUND FOR FIRST FRAME
*/
```
Frame2

```
stop();


//+++++++++++++++++++++++++++++ ADD EVENTSLISTENERS +++++++++++++++++++++++++++++

Btn1.addEventListener(MouseEvent.CLICK, RandomFrame);            // JUMP TO NEXT FRAME FUCNTION
stage.addEventListener(Event.ENTER_FRAME, CalculateDistance);    // CALCULATE DISTANCE AT EVERY FRAME RATE

//++++++++++++++++++++++++++++ FIRST TIME RANDOM JUMP +++++++++++++++++++++++++++
if (FirstJump == true){
	RandomNumber = Math.random() * 6;                            // GEMERATE RANDOM NUMBER BETWEEN 0 & 5.9999
	FrameNo = Math.floor(RandomNumber) + 2;                      // ROUND DOWN ADD 2 TO SKIP FRAME 1 & MAKE IT BETWEEN 2 & 7
	FirstJump = false;                                           // SETS TO FALSE SO THIS ROUTINE WILL NOT BE CALLED AGAIN
	gotoAndStop(FrameNo);                                        // JUMP TO RANDOM FRAME


}


//++++++++++++++++++++++++++++++++++ FUNCTIONS ++++++++++++++++++++++++++++++++++

function RandomFrame(event:MouseEvent):void {
//	MusicCh1.stop();                                             // STOP MUSIC
	RandomNumber = Math.random() * 6;                            // GEMERATE RANDOM NUMBER BETWEEN 0 & 5.9999
	FrameNo = Math.floor(RandomNumber) + 2;                      // ROUND DOWN ADD 2 TO SKIP FRAME 1 & MAKE IT BETWEEN 2 & 7
	while ( FrameNo == currentFrame){                            // MAKE SURE IT JUMPS TO A DIFFERENT FRAME THAN CURRENT ONE
		RandomNumber = Math.random() * 6;
		FrameNo = Math.floor(RandomNumber) + 2;
	}
//	MusicCh1 = Music1.play();                                    // START MUSIC
	gotoAndStop(FrameNo);                                        // JUMP TO RANDOM FRAME
}


function CalculateDistance(event:Event):void {
	Xvalue = (mouseX - Btn1.x) * (mouseX - Btn1.x);              // USING PYTHAGORAS
	Yvalue = (mouseY - Btn1.y) * (mouseY - Btn1.y);              // TO MEASURE DISTANCE THE MOUSE IS FROM THE BUTTON
	Distance = Math.sqrt(Xvalue + Yvalue);
	BackGround_mc.alpha = Distance / FadeDistance;               // THIS ADJUSTS THE ALPHA VALUE OF FADE RECTANGLE
	/*
	if ((Distance / FadeDistance) < 1){
		MusicVolume.volume = Distance / FadeDistance;            // WILL NOT LET THE VOLUME BECOME > 100% BUT
		MusicCh1.soundTransform = MusicVolume;                   // DECREASES MUSIC VOLUME
	}
	*/
}
```


----------

