Web DevCenter
oreilly.comSafari Books Online.Conferences.
MySQL Conference and Expo April 14-17, 2008, Santa Clara, CA

Sponsored Developer Resources

Web Columns
Adobe GoLive
Essential JavaScript
Megnut

Web Topics
All Articles
Browsers
ColdFusion
CSS
Database
Flash
Graphics
HTML/XHTML/DHTML
Scripting Languages
Tools
Weblogs

Atom 1.0 Feed RSS 1.0 Feed RSS 2.0 Feed

Learning Lab






ActionScript for Non-Coders
Pages: 1, 2


Related Reading

Flash Hacks
100 Industrial-Strength Tips & Tools
By Sham Bhangal

A Virtual Camera

One of the systems that Flash doesn't have that many other animation environments have is a virtual camera. Many professional animation systems allow you to set up a virtual camera that can itself be animated. This allows you to create the sort of camera work seen in traditional films, including pans, zooms, and fades.

Flash uses a more old-fashioned system based around a stage. Rather like a theater stage, the audience view is fixed, and it becomes harder to create the sort of close edits and camera effects we are used to seeing in Hollywood films.

Adam mentioned this one day in passing, to which I replied, "OK. If Flash doesn't have a camera, let's make our own."

Although a virtual camera sounds like a world away from the simple particle effect we just looked at, the way I did it is almost exactly the same. Again, there is no complex code, and the time to develop the camera was insignificant. It will, however, most likely save Adam literally days in some of his longer animations, because the alternative to a scripted camera is to simulate the camera pans, fades, and zooms using only tweens, and this can take a very long time to set up or change.

Adam sent me the animation in Figure 7 to illustrate the need for a virtual camera. The Flash stage is set up here to show a short scene in Adam's next production. The trouble is, he would like to create a number of camera movements and effects that are difficult with tweening. Although using embedded movie clips is one solution, the large number of separate animations needed in a typical animation make their use just as troublesome. We really need that Vcam to create a clean solution.

Figure 7. The waterfall. Click on the image to see the waterfall animation.
Figure 7. The waterfall. Click on the image to see the waterfall animation.

After some discussion (and a few failed trains of thought regarding what a Vcam should look like and do), we settled on the following implementation.

The Vcam will appear in the authoring environment as a rectangle that defines the Vcam viewfinder. You can download the source FLA for this animation here. Note that if you test the FLA, you will see the best results if you publish to the browser rather than view the result in the authoring environment (text movie will not cut out the content that appears outside the viewfinder, whereas the final effect when seen in a browser does). See Figure 8.

Figure 8. The virtual camera as seen in the Flash authoring environment
Figure 8. The virtual camera as seen in the Flash authoring environment.

All the animator has to do to use the camera is to tween the viewfinder around the stage. In the final animation, the code inside the camera component scales and pans the stage such that only the content within the viewfinder is seen. See Figure 9a.

Figure 9a. The virtual camera in use. Click on the image to see the flash animation in a popup
Figure 9a. The virtual camera in use. Click on the image to see the Flash animation in a popup.

The Vcam is nothing more than a simple component -- a rectangle with a short script attached to its first keyframe.

Here's the code that drives the camera:

function camControl():Void {
  parentColor.setTransform(camColor.getTransform());
  var scaleX:Number = sX/this._width;
  var scaleY:Number = sY/this._height;
  _parent._x = cX-(this._x*scaleX);
  _parent._y = cY-(this._y*scaleY);
  _parent._xscale = 100*scaleX;
  _parent._yscale = 100*scaleY;
}
function resetStage():Void {
  var resetTrans:Object = {ra:100, rb:0, ga:100, gb:0, ba:100, bb:0, aa:100, ab:0};
  parentColor.setTransform(resetTrans);
  _parent._xscale = 100;
  _parent._yscale = 100;
  _parent._x = 0;
  _parent._y = 0;
}
// make frame invisible
this._visible = false;
// Capture stage parameters
var oldMode:String = Stage.scaleMode;
Stage.scaleMode = "exactFit";
var cX:Number = Stage.width/2;
var cY:Number = Stage.height/2;
var sX:Number = Stage.width;
var sY:Number = Stage.height;
Stage.scaleMode = oldMode;
// create color instances for color 
// transforms (if any).
var camColor:Color = new Color(this);
var parentColor:Color = new Color(_parent);
// Make the stage move so that the 
// v-cam is centered on the
// viewport every frame
this.onEnterFrame = camControl;
// Make an explicit call to the camControl
// function to make sure it also runs on the
// first frame.
camControl();
// If the v-cam is ever removed (unloaded)
// the stage, return the stage to the default
// settings.
this.onUnload = resetStage;

The function camControl will run every frame. This function uses the position- and percent-scaling properties of the movie clip (_x, _y, and _xscale, _yscale) to continuously scale and move the stage so that the viewable content in the final movie is constrained to the stuff seen in the viewfinder (much as would occur in a real movie camera). See Figure 10.

As well as zooming and panning, we decided it would be cool to have some way of applying video transitions to the final content, allowing the camera to add fade effects as well as color tints (tinting can be important in adding ambience to an animation). Although using the color class in Flash can be daunting, the way the camera does it makes it very easy -- all the animator has to do is apply a color tween to the camera, and the following line (first line of camControl) will programmatically apply whatever color tweening it sees in the camera onto the stage (in much the same way that adding a color filter cap to a movie camera would tint the recorded movie in a real camera).

parentColor.setTransform(camColor.getTransform());

When the camera is no longer needed, the animator can delete it from the timeline. The code uses the event that occurs when a movie clip is removed in this way (onUnload) to cause the stage to be returned to the normal size. This is performed via the function resetStage.

It cannot be understated how useful we found the virtual camera in creating Flash animations that have the sort of pace and movement associated with mainstream cartoons and live-action movies. Although it may seem like a minor piece of code to a scripter, it is something that many animators have always found missing in Flash.

Of course, that's not a problem, because the Flash environment not only allows you to create your own content-creation building blocks, but in most cases, almost requires you to create them.

Finally, it is worth noting that, unlike a real camera, our virtual camera allows you to create distorted viewfinders. These result in stretched animations.

Figure 9b. A flattened viewfinder
Figure 10. The result (a vertically stretched movie)
Figure 9b, 10. The effects of using irregular shaped viewfinders: the image on the top shows a flattened viewfinder; the image on the bottomshows the result (a vertically stretched movie)

Although this may seem like a minor point to some (you can keep the viewfinder proportions the same throughout the animation if you hold down CONTROL every time you scale the camera with the scale tool), and a bug to others (it would be easy to add some code to the camera to make sure that the view was never distorted in this way), we left it in because it led Adam to a rather surprising hack: distorting an image as you zoom and pan can give a very cool, faux 3D effect.

Click here, here, and here to see this effect in action.

This works because the distortion makes the scene appear as if it is mapped onto a curved 3D surface rather than onto a flat plane.

So, in setting out to create a 2D virtual camera, we seem to have also stumbled onto a hacky 3D camera as well.

Bonus!

Also, I am working on integrating the camera as a custom tool in the Flash toolbar (via JSAPI), given that it is proving to be such a useful animation tool. It just goes to show how far Flash can be altered through scripting to make the process of creating content easier for both scripters and non-scripters.

Figure 11. A prototype camera tool (currently in production)
Figure 11. A prototype camera tool (currently in production).

Conclusion

Although many people wonder how the Flash authoring tool is used to create some of the Flash content out there, one of the big secrets is the way the authoring tool can be used to create building blocks to aid development via components, as well as optimize the authoring environment in other ways.

Despite the fact that many non-scripters find ActionScript off-putting, there is nothing wrong with that, and it shouldn't prevent them from gaining the advantages of scripting. ActionScript can easily be written and encapsulated within the workflow such that a designer or animator doesn't have to know about the code at all.

The creation of tools to change your workflow is not only useful in accelerating content creation, but can often throw up totally new techniques, as illustrated by our stumbling on a 3D-camera effect whilst developing a 2D camera. Working with Flash is like that!

Sham Bhangal is an author of and contributor to numerous books on Flash and ActionScript, including Foundation ActionScript for Flash MX, Flash MX Designer's ActionScript Reference, and Macromedia Flash MX Upgrade Essentials.


Return to the Web Development DevCenter.


In June 2004, O'Reilly Media, Inc., released Flash Hacks .


  • using final swf as loadmovie
    2005-06-24 10:25:10  digisam [View]

    this cam this is great, but when i load the swf into another movie, it takes the parents moves stage size and fills the screen

    anyway to restrict the cam to not scale 100% of the stage and only set cordinates?

    thanks

    sam
  • Very First Frame
    2005-06-28 17:24:48  Doki [View]

    Ok the Camera is great but when I insert it into a scene it seems to work for the whole scene APART from the very first frame, giving a rather annoying flicker effect. (I am using the flash 5 version)
  • fading?
    2005-07-07 06:23:34  shether [View]

    how do i fade with it?
    • fading?
      2005-07-19 17:26:05  Doki [View]

      Use the brightness fucntion and apply it to the neccessary keyframes.
  • Where to Download Virtual Camera component?
    2005-09-23 13:26:52  silverone [View]

    Hello!

    Where can one download this Virtual Camera compnonent?

    I don' t see a link in the article... Am I missing it?
    My eyes are going bad I know but....where is it?

    Is it Free or $???
    I'd be willing to pay for this. If it works, it is a great tool for a Flash arsenal.

    Is it Mac compatible, please say it is.

    • Where to Download Virtual Camera component?
      2005-09-24 13:09:00  Sham_B [View]

      http://www.oreillynet.com/javascript/2004/08/17/examples/waterfall02.fla. this fla contains the component in the library, so if you need it in another fla, all you have to do is copy it across.


      And yeah, its free :)

      S
      • Where to Download Virtual Camera component?
        2005-10-18 11:01:46  silverone [View]

        Many thanks dude!
        ;)
  • pause and play button.
    2005-11-14 10:58:05  cybexy [View]

    The vcam is great!!! I've started using it in all of my newer animations. The onlt problem i've had, (apart from the rotation problem) is that sometimes i like having a pause and play button at the bottom of my screen. However, with the vcam changing the area seen on screen, i haven't yet found a way to keep a pause/play button in the same place at the bottom of the screen. Any thoughts on how to stop this?
  • Wow
    2005-11-30 21:47:31  MaticooL [View]

    The swarm and the camera components help me a lot, thanks, the effect are just awesome!
  • Only one problem
    2005-11-30 23:16:55  MaticooL [View]

    I made the components from swarmEnvelope and Camera and they moved and became very ugly and moved outside of the area, what should I do?
    • Only one problem
      2005-12-01 03:23:09  MaticooL [View]

      Well, the problem is the resizing of component, when I resize the camera component or the swarm component, the component resizes but the content stays the same, why is that happening?
  • VCamera
    2006-01-05 15:46:35  toonboy1 [View]

    Hi,
    I tried to use the Vcam on my Flash animation but i couldn't get it to work. I downloaded the river example, and copied the Vcam from your library. When i tried to test movie i get this error message:

    **Error** Symbol=camFrame, layer=actions, frame=1:Line 1: '{' expected
    function camControl():Void {

    **Error** Symbol=camFrame, layer=actions, frame=1:Line 9: Unexpected '}' encountered
    }

    Total ActionScript Errors: 2 Reported Errors: 2

    Can you please help me....i was really excited that you can do animated zoom ins and outs with Flash.
    Thanks

    Wayne
    • VCamera
      2006-02-04 06:06:48  Sham_B [View]

      Are you using the correct version? there are different versions depending on which version of Flash you are using. Read the threads below and you should be able to find a link for your version (I suspect you may be trying to run the version for Flash 7 in Flash 6).

      S
    • VCamera
      2006-03-28 05:11:34  robincb [View]

      i can't open the .fla example in flash 5 or MX :S
      in flash it says failed to open document and in MX it says unexpected file format
      can someone help me? the script on the page gives errors too *is crying*
  • Window size
    2006-02-04 05:32:11  KKSlayer [View]

    Hi, the camera works great, but the problem i get is that if i choose any window size for the swf except of 720x480, the view screws up. I've only tested this with sprites, so that may be the problem, but it's really iritating that i must have the window size 720x480 to get it to look good.
    • Window size
      2006-02-04 06:09:40  Sham_B [View]

      It sounds as if the camera is assuming a standard screen size (4:3). IF you want to use any other size ratio, alter the size ratios of the camera symbol (edit the symbol itself rather than alter an instance on the stage) to match.

      S
  • Camera Bogs Down Movie
    2006-02-06 15:20:55  mrmyers [View]

    Hello,

    Are there any known issues with the camera slowing down the play rate of the movie itself. Just by havig the camera present in the movie (without adding any scaling or repositioning) the frame rate of my movie drops significantly. As soon as I take the camera off of the stage completely, the movie plays as it should. There are several functions in the code that depend on the setInterval command. Would this be culprit? Thank you for your assistance.
    • Camera Bogs Down Movie
      2006-06-25 17:47:27  vaisacht [View]

  • Rotation and blur rendering
    2006-02-17 21:44:52  Masterpingoo [View]

    Is it possible to update the code and allow the camera to make rotations, blur the picture as if someone try to make the focus...
  • fla file
    2006-07-17 14:12:32  Soliloquy [View]

    Hi,
    Thanks for the camera, but I can't seem to download the fla file... all that I get is a txt file full of jargon... any suggestions?
    • fla file
      2006-07-18 10:36:44  Soliloquy [View]

      I should add that the txt file shows up in the web browser, not as a download. I've tried to download it on Safari and Explorer, on a Mac and a PC.
    • fla file
      2006-07-20 15:38:42  Soliloquy [View]

      I don't know if you changed anything, but it downloaded properly. Thanks again for the camera.
  • Any more camera movement tutorials
    2006-07-18 21:27:12  Eddee14 [View]

    Thanks for the camera dude. SWEET!!!! Can you point me in the direction of some tutorials showing how to do some major camera moves, or should I just play around and see what I come up with?
  • masks
    2006-08-12 03:43:55  oggycheese [View]

    i put the Vcam on the top layer of my toon and then did panning and thing and when i exported it i noticed that it ignores the masks underneath, sometimes i started the Vcam at the edge of my cartoon and panned across to the other edge but you could see things outside the frame that i had masked. any way to stop this?
  • 3D efect
    2006-09-08 05:26:49  Allia [View]

    i understand that this camera can fake a 3D efect based on separate layers.
    I've created a simple "shape over shape" background diferent shapes on diferent layers. I move the camera with Keys but no 3D efect.. is there something i am missing ??
  • uhhhh
    2006-09-19 18:31:41  sasquatch13 [View]

    html>
    <head>
    <title>HI</title>
    </head>
    <body>
    Not sure what to put. Uhh..AwesomeSite.
    </body>
    </html>



  • uhhhh
    2006-09-19 18:35:42  sasquatch13 [View]

    Im having trouble with the vcam. My sticky dude's head turns black until my camera stops zooming out, then its the original color. Whats up with this?
  • uhhhh
    2006-09-19 18:35:46  sasquatch13 [View]

    Im having trouble with the vcam. My sticky dude's head turns black until my camera stops zooming out, then its the original color. Whats up with this?
  • uhhhh
    2006-09-19 18:35:48  sasquatch13 [View]

    Im having trouble with the vcam. My sticky dude's head turns black until my camera stops zooming out, then its the original color. Whats up with this?
  • does camera work if swf imported to after effects
    2006-10-23 06:16:28  madamblahblah [View]

    Hello,

    Has anybody tried to import their swf made on windows using the camera move into after effects for mac?

    I am about to make my flash animation but next month will have access to a studio to output it for DVD pal with sound.

    I would like to know if it's worth it to use the
    camera move as it's still early stages and if it won't work will try to do camera moves another way.

    thanks,
    squid
  • another javascript solution
    2006-11-04 03:12:38  peanch [View]

    Not sure if this will help - but here is one cool javascript image zoomifier - LuckyZoom - http://luckyteam.co.uk/products/LuckyZoom/
  • Error Messages
    2006-11-09 20:11:06  rockheadrumple [View]

    I seem to getting the same error messages another person wrote above, which outputs a message along these lines when exporting thr movie : **Error** Symbol=camFrame, layer=actions, frame=1:Line 1: '{' expected
    function camControl():Void {

    **Error** Symbol=camFrame, layer=actions, frame=1:Line 9: Unexpected '}' encountered
    }

    Total ActionScript Errors: 2 Reported Errors: 2

    **Error** Symbol=camFrame, layer=actions, frame=1:Line 1: '{' expected
    function camControl():Void {

    **Error** Symbol=camFrame, layer=actions, frame=1:Line 9: Unexpected '}' encountered
    }

    Total ActionScript Errors: 2 Reported Errors: 2

    I tried the camera on your Waterfall movie and it works fine when exported. I also tried to use the camera on a new project, zooming in on a single layer of paint. This also works fine. It just seems to be my current project that it wont work on. Why am I getting this message?

  • A Question?
    2007-01-18 02:23:52  MAHIYA [View]

    Hi Sham,
    The camera effect was very nice. I am new to Flash.I wanted to create waterfall for my project.Can you please help me. How did you create this waterfall? It looks so real. Can you please mail me the tutorial?
    Waiting for your reply.

    Thank you.
  • errors
    2007-01-30 11:43:51  FuzzySneaker [View]

    I've got the same problem as the guy two posts below me, about the expected and unexpected brackets. I've tried moving the brackets and taking them out and doing whatever with them, but nothing's working. What do I have to do to get beyond this error?
  • Exporting
    2007-02-13 11:36:05  braintreestudios [View]

    The VCAM is an awesome tool. But now im trying to export to a video file like a .mov but along with movie clips.. the VCAM doesnt work when i do this. any solutions
  • Colour gets screwed up
    2007-02-17 07:54:28  Freaktwa [View]

    Hi I've got flash 8 and I've just tried your vcam. It works but when I make something go grey the camera makes it black. I don't have a clue why. Any suggestions?
  • cant make it work
    2007-03-20 04:09:13  neverblink [View]

    sorry but im very new at flash especially in actionscripting. i do not know what to do here.
    i tried to copy & paste the code to my animation and made a rectangle but it did not work.

    can someone make a step by step process on how to make this thing work.

    oh yeah im only 16 hehe. really dont know anything about this.

    thank you
    • cant make it work
      2007-03-30 23:29:48  InvasiveInfection [View]

      yeah, i was stumped on how exactly to make this thing work, too. but it's actually pretty easy. all you have to do is go into the sample animation (the one with the waterfall) and click on the virtual camera (transparent box in the middle of the stage). then, it's just a matter of copying that virtual camera and pasting it directly onto the stage of YOUR animation. you might notice, on playback of any animation you make, the screen is black. this can be remedied by altering the brightness of the vcam from -100 to 0. then, motion tween away!!! note, however, that in motion tweening the black background can be used for fade ins and outs. duh.
  • Flash 5 Problem
    2007-06-09 05:58:00  Barbaro666 [View]

    Im A bit new to all this Scripting stuff, so i just cant figure something out
    I have flash 5, so i did put on the AS for Flash 5
    Still it has some errors & i just cant figure out how to repair them
    They are:

    Scene=Scene 1, Layer=Layer 1, Frame=1: Line 1: '{' expected
    function camControl():Void {

    Scene=Scene 1, Layer=Layer 1, Frame=1: Line 2: Statement must appear within onClipEvent handler
    parentColor.setTransform(camColor.getTransform());

    Scene=Scene 1, Layer=Layer 1, Frame=1: Line 3: Statement must appear within onClipEvent handler
    var scaleX:Number = sX/this._width;

    Scene=Scene 1, Layer=Layer 1, Frame=1: Line 4: Statement must appear within onClipEvent handler
    var scaleY:Number = sY/this._height;

    Scene=Scene 1, Layer=Layer 1, Frame=1: Line 5: Statement must appear within onClipEvent handler
    _parent._x = cX-(this._x*scaleX);

    Scene=Scene 1, Layer=Layer 1, Frame=1: Line 6: Statement must appear within onClipEvent handler
    _parent._y = cY-(this._y*scaleY);

    Scene=Scene 1, Layer=Layer 1, Frame=1: Line 7: Statement must appear within onClipEvent handler
    _parent._xscale = 100*scaleX;

    Scene=Scene 1, Layer=Layer 1, Frame=1: Line 8: Statement must appear within onClipEvent handler
    _parent._yscale = 100*scaleY;

    Scene=Scene 1, Layer=Layer 1, Frame=1: Line 9: Unexpected '}' encountered
    }

    (I do apologize for taking your time)

    Help on this Please
    Thank u!
  • movement speed
    2007-07-27 10:43:54  Kilaust [View]

    Im new to this whole site and everything, ive been working on an animation and iv'e pretty much figured out how to get the v-cam to move, but i cant exactly understand how to fix movement speed...does this involve the FPS by chance?
  • movement speed
    2007-07-27 10:44:15  Kilaust [View]

    Im new to this whole site and everything, ive been working on an animation and iv'e pretty much figured out how to get the v-cam to move, but i cant exactly understand how to fix movement speed...does this involve the FPS by chance?
  • the colors
    2007-08-06 14:53:28  deadya [View]

    hey, i just dl'd your .fla file, copied and put the vcam on a new file, in attempt to test it out, but whenever the vcam is in effect, everything is black until the vcam is no longer there, how do i fix this?
  • Thank you so much!
    2007-08-16 03:25:18  LogFish [View]

    Well I read a few comments and people are missing the point here - what you've done is a great service to the Flash community by making these components available to everyone like this - it's amazing what I've done in such a small amount of time! Now I can pan, zoom and shake the camera with no hassle AT ALL - it's brilliant, my animations are going to be so much more engaging - and it's thanks to you and your generousity, sharing them with everyone when you are under no obligation to do so. So from everyone who's too rude to notice, thank you so much! Legend. Truely.
  • <3
    2007-09-17 01:59:02  Quaay [View]

    OMG I love this tool!
    It's going to make my life soooo much easier
    for a flash assignment I have. & Just general
    flash usage.

    I am however getting the same error as a few others.

    **Error** Symbol=camFrame, layer=actions, frame=1:Line 1: '{' expected
    function camControl():Void {

    **Error** Symbol=camFrame, layer=actions, frame=1:Line 9: Unexpected '}' encountered
    }

    Total ActionScript Errors: 2 Reported Errors: 2

    **Error** Symbol=camFrame, layer=actions, frame=1:Line 1: '{' expected
    function camControl():Void {

    **Error** Symbol=camFrame, layer=actions, frame=1:Line 9: Unexpected '}' encountered
    }

    Total ActionScript Errors: 2 Reported Errors: 2

    I read it may be a version problem.
    I'm running flash 8.
    Anyone?

    thanks
    Ben
    • <3
      2007-11-20 21:08:09  darkace [View]

      When I was using the code I was getting the same error messages. Then I tried making a new document in actionscript 2 vs actionscript 3 which I was in. Actionscript 2 worked out. By the way I am using Flash CS3, but hopefully this works for you or anyone else having problems.
  • Movie Clips the Camera doesn't see?
    2008-02-20 16:09:06  Ramiel [View]

    Is there a way to have an object OVER the camera, that isn't modified by the code of the camera? I'm trying to add scrolling text over a scene I have with the camera, and I'd love to know if this is possible! (Flash CS3 Pro, I believe I have the Flash 8 version of the camera.)
  • Wondering
    2009-08-16 11:13:43  TanLiqingVivien [View]

    Oh I was just wondering how did u create the 3D flaux effect..