Thursday, December 24, 2009

Christmas Hurl



I recommend going to the large version here and saving the .swf to your desktop.

The holidays are here! In celebration, I've whipped up the above. It's a simple little tree decoration thing that showcases a few concepts. First off, we have gravity and physics. As each ornament falls, it picks up speed, giving the illusion of gravity pulling. Surprisingly, faking gravity is INCREDIBLY easy! You see, each movie clip is moving a set amount every frame (shown as _y+=dy where dy is a number). The trick here is that the "dy" constantly increases by a set amount. So let's say dy starts at 0 but increases by 1 every time.

Frame1:
dy = 1
old _y = 0
new _y = 1

Frame 2:
dy = 2
old_y = 1
new _y = 3

Frame 3:
dy = 3
old_y = 3
new _y = 6

and so on...but remember, you're likely running around 24 -31 fps, so your change in dy should probably be tiny (experiment with this to simulate different gravities! I tend to use .1 as a baseline, but it changes depending on how I want something to move).

Speaking of dy, the bouncing effect is a neat little trick, too. When the movie clip hits the bottom, it is first moved to the bottom edge of the screen (if something is moving fast enough it goes PAST the bottom of the screen, so this rights it) and then it's dy is multiplied by -.7. Why not -1? In the real world, some energy is lost to the ground when a ball bounces (ever have a really heavy box fall beside you? Even if you didn't get hit, you definitely felt the box thud! That's the dissipated energy...some of it, anyway).

The last little bit I'll share with you is how to calculate the speed of the thrown object. To be honest, this was an experiment that I really didn't expect to work. But surprise! Work it did. Essentially, we're keeping track of two values. Where the mouse is NOW and where the mouse was a frame ago. These values are updated every time the mouse moves, and the difference between the two is stored as a number. When you release the ornament, that difference is used to determine the speed of the the thrown object. Nifty, eh?

Well, that's it for now. Merry Christmas!

No comments:

Post a Comment