11 Replies Latest reply on Sep 24, 2017 9:16 AM by ClayUUID

    AS3 How to Random image?

    Vincent Alim

      Hi guys,

      I want to create a random logo button from several movie clip. How to start it?

      I've already create some movie clip with a logo on it with name : mc_1, mc_2, etc. It will be 32 or 35 logos.

       

      the rules:

      1. only 1 logo come out, and changed after another click.

      2. same logo might appear again

       

      I've browse some tips in this forum with different method like:

      1. this.addchild (i don't understand how it is work)

      2. using gotoAndPlay with random frame (I know the mechanism, but didn't understand how to create the random number)

      3. another tips?

       

      Thanks in advance!

       

      This is the example.

       

      2017-09-24.png

        • 1. Re: AS3 How to Random image?
          RandomlyFish Level 3

          To add a symbol from the library it first needs a linkage, you can add that from the library panel if you double click below where it says linkage. If the linkage is Logo:

           

          // Automatically gets added when declaring a variable with the type MovieClip
          import flash.display.MovieClip;
          
          // Variables for the logo position
          var logoPositionX : int = 100;
          var logoPositionY : int = 100;
          
          // Create a new Logo instance from the Library and store it
          var logo : MovieClip = new Logo();
          
          // The number of logos
          var logos : int = 8;
          
          // Add it to the stage
          stage.addChild(logo);
          
          // Change it's position
          logo.x = logoPositionX;
          logo.y = logoPositionY;
          
          // Function for randomly picking a logo
          function RandomLogo () {
          
               // Math.random() returns a value between 0 and 1 which is then multiplied by the number of logos, lastly it's stored as a whole number
               var random : int = Math.random() * logos;
          
               // Go to and stop on the randomly selected frame, 1 is added since frame numbers starts with 1 in Actionscript
               logo.gotoAndStop(random + 1);
          }
          
          // Run the function
          RandomLogo();
          

           

          If you're going to change frames inside a symbol, you could just use a symbol that's already placed on the stage, I just thought I would include an example for adding a symbol from the library.

           

          You can see more things you can do with the math class here: Math - Adobe ActionScript® 3 (AS3 ) API Reference

          • 2. Re: AS3 How to Random image?
            Vincent Alim Level 1

            Hi, thanks for the help. I will try your after this one. Before read your answer. I've tried this code. But, doesn't work perfectly (or maybe you could help to find the problem)

             

            This is the script I've found. It works, but when I've add a button to generate the random / regenerate, the script is error.

            If I deleted the button, without addEventListener Mouse Click, it works perfectly. But it is not good if I have to re-open my SWF file everytime I want to regenerate the logo. This one only needs frame.

             

            Here is the code :

             

             

            import flash.display.Bitmap;

            import flash.events.Event;

            import flash.net.URLRequest;

            import flash.display.Loader;

             

             

            var imgRequest:URLRequest;

             

            var randCount:int = 31*Math.random();

             

             

            btn_random.addEventListener(MouseEvent.CLICK,loadImage);

            function loadImage():void

            {

                for(var i:int = 1; i<randCount; i++)

                {

                    var imgLoader:Loader = new Loader();

                    imgRequest = new URLRequest();

                    imgRequest.url = "img/img" + int(31*Math.random()) +".jpg";

                    trace(imgRequest.url);

                    imgLoader.load(imgRequest);

                    imgLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, unloadedImg);

                    imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadedImg);

                }

            }

             

             

            function onLoadedImg(e:Event):void

            {

                e.currentTarget.removeEventListener(Event.COMPLETE, onLoadedImg);

             

             

                var bmp:Bitmap = e.currentTarget.content;

             

             

                bmp.x = 534

                bmp.y = 418

                bmp.width = 500;

                bmp.height = 500;

                this.addChild(bmp);

            }

             

             

            function unloadedImg(e:IOErrorEvent):void

            {

                e.currentTarget.removeEventListener(IOErrorEvent.IO_ERROR, unloadedImg);

                trace("load Failed:" + e);

            }

             

             

            loadImage();

             

             

            The error code (after I've added random generate logo) :

            img/img21.jpg

            img/img18.jpg

            img/img28.jpg

            img/img1.jpg

            img/img28.jpg

            img/img21.jpg

            img/img7.jpg

            ArgumentError: Error #1063: Argument count mismatch on random_fla::MainTimeline/loadImage(). Expected 0, got 1.

             

             

            Thanks a lot, mate!

            • 3. Re: AS3 How to Random image?
              ClayUUID Adobe Community Professional

              Why are you trying to load images at runtime? Just import them into the library.

              1 person found this helpful
              • 4. Re: AS3 How to Random image?
                Vincent Alim Level 1

                sorry, I'm a beginner.

                After I import the images to the library, then what?

                 

                which part of my script I need to change?

                • 5. Re: AS3 How to Random image?
                  RandomlyFish Level 3

                  The reason why you get the error is because the loadImage function is missing the "e : MouseEvent" paramter. So your loadImage function didn't expect any arguments passed to it, but it got 1 from the mouse event.

                   

                  So I would recommend creating a function called loadImageButton, that's used for the mouse event, and make that function call the loadImage function.

                  1 person found this helpful
                  • 6. Re: AS3 How to Random image?
                    Vincent Alim Level 1

                    wow it is running well know as I want!
                    Thanks mate!

                     

                     

                    Thanks a lot RandomlyFish and ClayUUID

                    • 7. Re: AS3 How to Random image?
                      ClayUUID Adobe Community Professional

                      RandomlyFish  wrote

                       

                      The reason why you get the error is because the loadImage function is missing the "e : MouseEvent" paramter. So your loadImage function didn't expect any arguments passed to it, but it got 1 from the mouse event.

                      You just helped him do it the wrong way. Now there will be a delay every time each image is loaded for the first time, instead of having it appear instantly as a preloaded image would.

                       

                      Vincent, the easiest, most correct way to do this (assuming there is no business need for the logos to be external files), is to load every logo into Animate, create a movieclip, and put each logo in its own frame of the movieclip. Then you can display logos by just telling the movieclip to go to a specific frame.

                      1 person found this helpful
                      • 8. Re: AS3 How to Random image?
                        RandomlyFish Level 3

                        My original code suggested using keyframes, but it's ultimately up to them how they want to implement it.

                        • 9. Re: AS3 How to Random image?
                          Vincent Alim Level 1

                          Yes, there is a delay like 0.5 - 1 sec. But at least, it is work.
                          I will try your script after this, for a better loading time.

                          • 10. Re: AS3 How to Random image?
                            RandomlyFish Level 3

                            You can quickly add multiple images to different keyframes if you select all the images in the library and drop them on the stage. Then with them selected, you can right click on them and select distribute to keyframes.

                            • 11. Re: AS3 How to Random image?
                              ClayUUID Adobe Community Professional

                              RandomlyFish  wrote

                               

                              My original code suggested using keyframes, but it's ultimately up to them how they want to implement it.

                              True and true. But newbie coders have a really bad habit of latching onto the first thing that resembles a solution to their problem and developing a severe case of tunnel vision towards making it work. This is how bad code, and bad coders, flourish in the world. It's the responsibility of more experienced developers on help forums to not just help people make their code work, but also to guide them to more appropriate solutions. Aiding and abetting a bad solution just does long-term damage.