Search code examples
actionscript-3animationflashdevelop

as3 animation with multiple images


I have only 3 images that I'm working with for animating a running animal: 1: animal standing 2: animal in stride/jumping 3: animal on its back dead

Currently, I'm embedding them into the main class as sprites and changing their .alpha properties whenever I want one and not the other 2. Is there a better way to do what I'm doing? One of the annoying things is updating the properties for each sprite individually. It would be ideal to have one object and being able to change the image on the object so I would only have to change one object's properties.


Solution

  • For this it would be best to handle your animation in its own Class! Something like this, let's say your animal is a horse so that's what I'll call the class

    package  {
    
        import flash.display.Sprite;
    
        public class Horse extends Sprite{
    
            private var holder:Sprite = new Sprite();
    
            public function Horse() {
    
                var img1:Image1 = new Image1();// ur images from library
                var img2:Image2 = new Image2();
                var img3:Image2 = new Image3();
    
                holder.addChild(img1);
                holder.addChild(img2);
                holder.addChild(img3);
    
                addChild(holder);
                setImage(0);// set 1st image visible
    
            }   
    
            public function setImage(nr:uint):void
            {
                for(var i:int = 0; i < holder.length;i++;)
                    holder[i].visible = false;
    
                holder[nr].visible = true;
            }
        }
    
    }
    

    then you would use it like this for example!

    var horse:Horse = new Horse();
    addChild(horse);
    horse.x = 25; 
    horse.y = 25; // move the whole object(all 3 images)
    horse.setImage(2);// or to whatever frame you need
    

    Use the visible attribute instead of the alpha value. If u just set alpha to 0 it will still be rendered and cost cpu. if you set visible to false it will not be rendered!

    EDIT:
    As Amy pointed out, blitting is a possibilty here to, although the fastest aproach would be BitmapData Frame Assignment! Here you keep all your Frames as BitmapData in a Vector, which you load from a SpriteSheet and just assign the new BitmapData to your Bitmap instead of using copyPixels. It's faster then blitting and you still have all your builtin methods availible!!