Samsung NX10: A Digital SLR in a Compact Hybrid Body

Samsung’s managed to cram a Digital SLR sensor into a compact hybrid body, but how does the NX10 perform? We’ll be taking an in-depth look at this new concept from Samsung.


Why All the Fuss?

The Samsung NX10 has been getting a huge amount of attention because it’s the first mirror-less digital SLR hybrid with an APS-C format sensor. It’s true that the Micro Four Thirds format cameras from Olympus and Panasonic have been out for a while, but they use a smaller sensor format. The key questions are, then, whether the NX10 can compete on level terms with digital SLRs, and whether it offers any quality advantage over Micro Four Thirds?

Hybrid cameras have many advantages and one fairly major disadvantage. The advantages include smaller, lighter bodies with fewer moving parts (there’s no need for the mirror or pentaprism used by SLRs) and full-time live view. This makes them easier to understand for users migrating up from a compact digital camera.

The disadvantage is that you have to make do with an electronic viewfinder rather than the optical viewing system of a digital SLR. Even with the latest high-res EVFs, it’s a big difference. You don’t get the same definition or clarity in mixed lighting conditions, and it’s harder to judge the focusing visually.


Key Specifications

The NX10 is a new approach from Samsung. Previous forays into the digital SLR market were conventional digital SLRs produced in partnership with Pentax. The badges and some interface elements were different, but essentially the Samsung GX10 and GX20 were Pentax cameras in disguise. The NX10, though, is Samsung’s own design.

The specifications are quite impressive given the NX10’s price. They include a 14.6-megapixel CMOS sensor with a maximum sensitivity of ISO 3200, a 3-inch ‘AMOLED’ display (seen here) with 614,000 dots and a 1280 x 720 HD movie mode.

The standard kit lens is an 18-55mm f3.5-5.6 with Samsung’s own Optical Image Stabilizaton system, but there’s also a 50-200mm f4-5.6 OIS telephoto zoom and a 30mm f2 fixed focal length ‘pancake’ lens available separately.

The NX10 has all the manual controls and features you’d expect from a digital SLR, including full program AE, aperture-priority, shutter-priority and manual modes and the ability to shoot both JPEG and RAW files. RAW files can be processed using the Samsung RAW Converter software that comes with the camera, but this is a PC-only program so Mac owners will have to wait for third-party software publishers to add support for this camera.

Beginners needn’t feel intimidated, though. The NX10 comes with a range of scene modes which can be selected manually and a Smart Auto mode where the camera analyses the scene and chooses the on that’s most suitable. The autofocus system offers a face-detection mode, and there’s a Beauty Shot mode for enhancing portrait shots.


Look and Feel

On paper, the NX10 looks pretty good. In the flesh, it’s even better. The body is certainly smaller than a digital SLR’s and, because there’s no mirror, a whole lot slimmer. You can see just how slim the body is in this overhead shot (though the kit lens is a good deal fatter than the 30mm ‘pancake’ lens fitted here).

In fact the Samsung is no bigger than Panasonic’s G-series SLR hybrids, despite the fact that its APS-C sensor has around twice the area. Olympus’s Pen cameras are a little smaller, though by the time you’ve extended Olympus’s retracting 14-42mm lens, it’s actually longer than the Samsung’s.

The design and the finish and the feel of the controls are equally impressive. The NX10 feels light, comfortable and sturdy in your hands. The power switch (around the shutter release), the top control wheel, and the mode dial have a firm, positive feel. The buttons on the back are perhaps a little small – especially the directional controller – but they’re clearly labelled and work well.

Samsung’s menu system has been designed to be more straightforward for beginners, but the position of the menu button above the top left corner of the display is quite odd – you keep expecting to find it with the other buttons near the navigational controller.

It’s also a bit too easy to accidentally press the white balance button (the right navigational button) with the heel of your right thumb as you hold the camera. The display is pretty busy, with icons running down both sides and shooting information along the bottom, and it’s a shame there isn’t some kind of simplified interactive display where you can highlight the setting you want on the screen and change it directly.

Whether or not it is aimed at beginners, the NX10 also has all the features more experienced and adventurous photographers will be looking for. As well as auto-exposure bracketing, it offers white balance bracketing and Picture Wizard bracketing too. Picture Wizards are Samsung’s name for picture styles like ‘vivid’, black and white, ‘natural’ modes and more.

Like other manufacturers, Samsung offers a mode which attempts to control highlights and shadows in high-contrast scenes, effectively extending the camera’s dynamic range. It’s called ‘Smart Range’, and it’s comparable to Nikon’s ‘Active D-Lighting’ and Sony’s Dynamic Range Optimizer. Here, it’s held on to the detail in this rock as well as the brighter landscape and sky in the background.


Viewing and Focusing

Samsung says the AMOLED (Active-Matrix Organic Light-Emitting Diode) display is thinner, brighter and offers better response times than conventional displays, as well as excellent colors. It doesn’t look that different to other displays, to be fair, though it does offer extremely wide viewing angles. That could be useful, because the display is fixed and doesn’t swing out and rotate like the Panasonic G1/G2’s, for example, or Nikon’s D5000 digital SLR.

The electronic viewfinder is a little less impressive. It has much higher resolution than those in compact superzoom cameras, but it still looks slightly pixelated, and it doesn’t show much detail in darker areas. This is the price you pay with hybrid SLR designs, but for many users it will be well worth it because of the advantages.

The full-time live view offered by the NX is massively superior to the live view you get with a digital SLR. You don’t get the delay and the mechanical noise as the mirror flips up out of the way, and the autofocus is much, much quicker. If you prefer using an LCD to a viewfinder to compose your shots, the Samsung’s mirror-less design is a better long-term choice than a digital SLR.

The manual focus mode isn’t bad either. The problem here with the hybrid design is that an electronic viewfinder isn’t as good as an optical finder for judging focus. The NX does magnify the viewfinder image when you turn the focus ring, which makes it easier to judge when your subject is sharp, but it’s still not quite as quick or as positive as a digital SLR.

Sometimes manual focusing is essential, even with the most sophisticated multi-point AF system, especially when your subject is on an angled plane like this and you want to exploit shallow depth of field.

The focus ring doesn’t have a distance scale, though, so you can’t use old-fashioned zone focusing and depth of field control. But the lens does use internal focusing, which means that the front element doesn’t rotate, so there’s no problem using polarizing or graduated filters.


Movie Mode

The movie mode works well, too. The autofocus still works as you film (though face-detection mode is not available), and keeps up reasonably well as long as your subjects don’t move too quickly. The footage can get very ‘choppy’, though, if you don’t keep the camera still, and this seems to be a feature of HD cameras in general – the extra resolution tends to make poor shooting technique all the more obvious. The in-built microphones do suffer from wind noise, but there’s a Wind Cut function which helps reduce it.

The lack of an external microphone socket will limit the Samsung’s appeal for real video enthusiasts, and there are no manual exposure controls in the movie mode, though you can set the lens aperture manually, choosing a large aperture to get a ‘cinematic’ look with reduced depth of field, for example. You can apply fade in/out effects to your clips, too.

You can play movies back on an HDTV using the camera’s HDMI interface, though you’ll have to buy the cable separately. It’s compatible with Samsung’s Anynet+ system, so if you own a compatible Samsung TV you should be able to operate the camera in playback mode with your existing remote.


Picture Quality

The main point about the NX10, of course, is that it should provide digital SLR quality, and it certainly does that. You won’t necessarily see much difference in definition from the 14-megapixel files this camera produces compared to the 12-megapixel images of Micro Four Thirds cameras or Nikon’s digital SLRs, but then Canon’s 15 and 18-megapixel APS-C SLRs aren’t any sharper either.

What you do get with the Samsung are clean, clear, richly-detailed images with plenty of saturation and contrast. In fact, sometimes the colors can be a little overpowering. The ‘Vivid’ Picture Wizard was used for this shot to make the most of the bright seaside colours.

It’s not bad at high ISOs, either. At the ISO 3200 maximum, the quality is pretty borderline, but at ISO 1600 it’s fine. It’s well up to current digital SLR standards and, if you’ve just moved up from a compact, you will be amazed at the quality improvement you get from the bigger sensor.

The 18-55mm kit lens is especially good. It’s light and compact, and the zooming and focus actions are very smooth. It delivers sharp detail right up to the edge of the frame, and there’s very little chromatic aberration or distortion. In fact as kit lenses go, it’s one of the best.


Is It a Serious Contender?

With its full-time live view, the NX10 has some appeal for beginners simply because it’s a more straightforward step up from a compact, but all the rest about hybrids being easier to understand than D-SLRs is a myth. All digital SLRs have full auto modes than any beginner can operate, and they always did have. The NX10’s mirror-less design makes it simpler for those used to compacts, but its in-depth features and controls are just as complicated as an SLR’s.

The NX10 is a great camera nonetheless. It’s cheaper, lighter and simpler than a D-SLR and yet delivers the same image quality and features. The current line-up of three lenses and a pair of external flashguns (the larger ED-SEF42A flash unit and 50-200mm lens are shown above) is a little restricted, but it’s early days yet and as long as Samsung adds more lenses over time, the Samsung should prove a strong rival both to Micro Four Thirds cameras and low-end to mid-range digital SLRs.

It’s a little harder to split these three groups of cameras for quality. Micro Four Thirds sensors might be physically smaller, but a process of constant development has yielded a level of image quality that rivals APS-C sensors, despite the size difference, and Olympus and Panasonic also produce some very sharp, low-aberration lenses.

The definition in this shot is exactly what you’d expect from an APS-C sensor. The NX10 has a slight megapixel advantage over many of its rivals, but it’s not enough to make any obvious difference to the pictures.

That doesn’t mean the NX10 underperforms. Quite the contrary – its rivals set very high standards, and it’s to the Samsung’s credit that it matches them.


Verdict

Samsung’s first APS-C format hybrid SLR has been a little while coming, but it really has been worth the wait. The NX10 is surprisingly compact, well-made, and stylish. It handles well and takes top quality pictures too. It proves that APS-C hybrids can work as well as D-SLRs, and it comes in at a very competitive price.

Pros

  1. Size, design and handling
  2. Fast autofocus
  3. Overall picture quality
  4. Kit lens performance

Cons

  1. No external mic socket or manual controls for HD movies
  2. Average-quality electronic viewfinder
  3. Limited lens range so far

Quick Tip: 3 Creative Uses of Slow Shutter Speed

Experimenting with shutter speed on your camera is a simple way to achieve some great effects. We’re moving beyond the idea of simply capturing more light today, and showcasing three ways in which you can do something a little different with a slow shutter speed.


1. Light Painting

Light painting is a fairly broad term, used to describe all manner of different techniques. In this Quick Tip, we’re talking about the idea of selectively adding light to a dark scene, illuminating only the areas you choose to. It’s a great way to emphasise certain aspects of a composition.

You’ll need a fairly dark scene, and something bright to shine on the parts you’d like to “paint with light”. This could be a torch – great for larger, outdoor scenes – or something like a candle for far smaller compositions.

We actually posted a video tutorial on how to do this a few months ago, which talks through the whole process:

Don’t forget that you’ll most likely need a tripod and, ideally, a cable shutter release to ensure that your shot remains crisp and sharp.


2. Light Graffiti

Light Graffiti again involves a very dark scene and a long exposure, but rather than painting a subject with light, the light itself becomes the subject. You’ll want something really bright – a torch, glow stick, or anything similar can work well. Experimentation is key, and it might take a while to get the effect you’re looking for.

Try drawing letters and spelling out a message, tracing the outline of an object in the scene, or drawing your own cartoon. If you can get the exposure just right, it’s also fun to use light to interact with other objects in the scene, as shown below:

Experimenting with your own light graffiti is, quite simply, great fun. You don’t need expensive equipment, just plenty of time and a creative imagination. Start with an exposure time of several seconds, and adjust it depending upon the result. As with light painting, a tripod is an absolute must.


3. Make Time Stand Still

The final technique to discuss centres around movement rather than light. Keeping one subject within your photograph completely still while everything else moves creates a fantastic effect:

This is a wonderful way to capture motion in an image – something that can be really difficult to achieve. Because you’ll likely be shooting in a lighter environment, the shutter speed used won’t need to be as long as either of the above techniques. It might be possible to hand hold the camera for shots like these, but for better, crisp results you’ll still need a tripod and some careful planning.

Coupling a flash with this technique gives you an even greater range of options to experiment with. We posted an in-depth tutorial on this several months ago, entitled How to Use Flash With a Slow Shutter to Create Motion and Ghosts. It’s a great place to start when experimenting with a slow shutter speed and flash photography.


Share Your Images

Have you captured any images that fall into the above categories? I’d love to see them. Feel free to post a link in the comments below.

To Read or To Listen?

Thanks to the dawn of “The eBook Era,” reading is becoming more accessible (if not necessarily more popular – thanks still to television).  If you have an iPad or Kindle (or one of the many eReaders in the marketplace) or simply use another mobile device, ebooks are literally in the palm of your hands.  These devices allow the user to carry a catalog of books that would fill a backpack (and then some!), making it easy to carry around whatever books you’d like to have at your disposal.

But what about audiobooks?

Formerly known as “books on tape” these are still popular in that you can absorb the story while driving or commuting in some other fashion.  If you’re exercising you can have them at the ready on your MP3 player of choice.  Basically, they fill a similar gap as podcasts – only they’re a “tad” longer.

Productivity and self-development books are massively popular in both formats.  You can even buy them in (gasp!) actual printed book form should you choose to.  In terms of brushing up on these skills and systems, which do you prefer – reading or listening…or a combination of all formats?

Composite A Live Action Jet Flyby – AE Part

In this 2 Part, 45 minute tutorial we’ll go over the process involved with compositing a jet, helicopter, or even a UFO into your live actions scenes. You can watch Part One over on CGtuts+ before you watch Part Two below.


Preview

Want access to the full AE project files and assets for every tutorial on Aetuts+, including this one? Join Ae Premium for just $9/month. You can view the final effect preview video below.

Tutorial

Download Tutorial .flv

File size 192MB


Inspiration: 45 Examples of Illustrative Lettering in Vector


From the very first Phoenician alphabet, through Chinese calligraphy, to illuminated manuscripts, and to desktop publishing, the written word has been one of our primary means of communication. Not content with plain text on a blank background, artists through the centuries have created beautiful, awe-inspiring designs with type. Whether its purpose is to inspire or identify, illustrative lettering communicates to the heart as well as the head.

Continue reading “Inspiration: 45 Examples of Illustrative Lettering in Vector”

Modeling the Human Body in Adobe Illustrator


In this tutorial we will use Adobe Illustrator to create the ideal proportions of a female figure. Factors such as race, sex and personality do not allow us to apply strict rules concerning proportions. By learning the skills in this tutorial you will be well on your way to drawing any shape and size of body. Let’s get started!

Continue reading “Modeling the Human Body in Adobe Illustrator”

How to Work in Audio: Careers in Sound

Interested in working in audio? Do you love music and wish you could work with sound? Did you go to audio production school because you thought it was cool, only to find out that you had no idea where to start looking for a job when you graduated?

Audio and sound related careers are varied and diverse, with many different industries needing qualified (or at least interested) sound engineers. This ranges from the obvious recording studio work to lesser thought of sound design, foley recorders and game design. In the next few posts I’ll guide you through the different careers you can hope to achieve with your audio enthusiasm, from big commercial studio work, entrepreneurial business endeavors to creating sound effects for video games.


Music

The most popular place for many audio engineers is to work in music. Everybody wants to have their hands in the next hit, and there are certainly many positions to be had in a big recording studio.

The various phases of a production can be broken down into their respective job titles. As you may well know, there are different stages of a production, the recording and production phase, where tracks get recorded and music gets produced, the mixing session where the multi-tracks get mixed together into one cohesive and well blended mix and then finally a mastering session where the mix gets finalized. Therefore, there are dedicated audio engineers that like to specialize in a certain aspect of the production process.


The Recording Engineer

Do you like mics? Do you like the technical aspect of the production process, all the various sounds you can get by finding the correct pre-amp, the right microphone and the perfect position? Then being a recording engineer is definitely up your alley. Experimenting with various recording equipment and getting a great source sound is the pride of the recording engineer, and is great for those who like working around musicians and artists in the studio.

However, the downside of being a recording engineer can be odd hours and tedious recording work as you try to punch in that last vocal phrase for the fiftieth time at two o’clock in the morning. The payoff of witnessing an amazing performance from a brilliant artist may outweigh the cons of working weird hours, and might not even be considered a bad thing if you are a B person who likes working nights anyway.


The Mixing Engineer

When the production process has been finished, every instrument has been recorded and all the musicians have gone home it’s time for the multi-track to be mixed. If we take a typical multi-tracked recording that’s been recorded over the span of a few weeks or months (or God forbid years!), there can be severe inconsistencies in levels and sounds that each particular instrument has.

We can’t go and put all the faders level with each other can call a track mixed, since the instruments were all recorded at different levels. Some instruments that were meant to be in the background might have been recorded much hotter than a lead element therefore dominating the mix. So it’s the mixing engineer’s job to square off these tracks and create a consistent and exciting mix out of the recorded multi-tracks he gets from the recording engineer.

Whereas the recording engineer’s job was to capture the most beautiful and full sound out of every instrument, it’s the mixing engineer’s job to trim the fat from every instrument, making sure all the instruments can be heard and appreciated. So although the recording engineer recorded a beautiful and full bodied guitar part during the recording process, it might end up heavily filtered and processed to fit the song at the end of the mixing process.

If you like working with pre-recorded music, and like fiddling around with EQ and compression alongside effects processors and reverb, being a mixing engineer can be a great vocation. It can be nice to immerse yourself in a mix without having to deal with the actual artists until the mix is done. It enables you to work the hours you want and it can also get very inspirational and creative trying to mold a consistent and flowing mix out of randomly recorded tracks. So when you’ve finally drained your creative spirits and ended up with an amazing mix, you can call in the artists to get their final comments and ultimate approval.


The Mastering Engineer

The final link in the production chain is the mastering process. Working as mastering engineers, it’s our duty to make the master sound better than the mix, and also make multiple songs sound like a complete whole.

Ever wondered how CDs that were recorded in 10 different studios can be made to sound similar to one another? A lot of it has to do with the mastering process, as the mastering engineer goes over every track that the artist has recorded and tries to make it sound like a complete package.

With subtle compression and EQs, a mastering engineer shapes a mix into an exciting an aurally dynamic package. If you like using subtle compression, EQ and limiting to put the final touches to an already great sounding mix, but making it sound better, then being a mastering engineer can be a good idea for you. It’s their job to take an exciting mix that might be too dynamic or needing a repairs in specific frequency regions and really make it shine.


Assistants

Barring the fact that you just create your own studio and become a no holds barred jack of all trades, recording, mixing and mastering everything yourself, you’re probably not going to start your career in a big studio being the big muscle mixing engineer. Starting as an assistant or an intern is usually the way to go.

Assisting under skilled and professional engineers, regardless of which facet of the production process they work in, can be an invaluable learning experience. Learning the trade first-hand from someone with plentiful experience can be a quicker way to learn the craft since you can tap into the wisdom and experience of someone who has gone through hundreds of songs and recordings.

I highly recommend interning or assisting for experienced engineers as they can give you quick productive answers based on experience in a heartbeat as opposed to you leafing through hundreds of pages of books, blogs or forums to get a trustworthy answer to audio related questions. Experienced engineers can be a pool of knowledge and experience, and the payoff of taking a minimal, or non-paying job working for them is the immediate access to experience that can help you in the long run.


Conclusion

The music industry is a popular one. Many of those who dive into the world of audio engineering do so with the intent of wanting to work with music. It’s the industry that first pops into our heads and is one of the more exciting and glamorous ones to work in, with the Lady Gagas and Justin Timberlakes of the world. Who doesn’t want to have “Recent clients include Lady Gaga” on their resume? C’mon! Don’t lie! The fact is that the amount of artistic and creative juice flowing in the music industry is contagious, and everybody wants a piece of the cake. So if you can handle the incredibly competitive nature of the music industry and have the talent to make a name for yourself, you could do worse things than putting your passion for audio into the music industry.

What’s your career in the music industry? Do you currently work as one of these, or are you planning on pursuing a career as an audio engineer in music? Stay tuned for the next installments of careers in audio as we talk about broadcast and film work, recording foley, supervising radio broadcasts or mixing film scores.


Not What They Seem: Deceptive Vexel Artworks


Vexel is a form of pixel-based raster art that imitates the appearance of what we know as vector graphics; smooth, sharp-edged illustrations that can be scaled up and down. Vexel art, however, is created using pixel-based shapes that are layered upon each other to create stepped but gradual color transitions. Gradients are sometimes used to give the artwork a more detailed and smooth look, but at the end of the day, no matter what technique has been used, the final outcome is a rasterized image that can’t be scaled. This technique is typically used by those who are more comfortable with programs like Photoshop, rather than alternative vector-based apps.

Due to the amount of detail that can be put into an image using the vexel technique, it is a great process to use if you want to replicate images of both humans and animals, as well as landscapes. It can also be used to create illustrations like those we see being produced in vector-based applications like Illustrator. This post showcases 45 wonderful examples of vexel artwork for your inspiration. What’s your favorite?


Animals

Chi

Law of Survival

A great vector-style illustration that demonstrates that no matter how colorful and happy the world is, there will always be someone bigger than you willing to eat you up!

Equus

It’s Bacon

A very impressive and detailed vexel piece by Amanda Schubert, just imagine how many layers were in this PSD file!

Googly-Eye Animals

Squirrel Love

An incredibly cute vexel print piece of two squirrels in love. The main shapes of the design were produced in illustrator, and once rasterized were colored in Photoshop, making it fit into the vexel category.

I Am A Bird

Unicorn

This piece falls under the subcategory ‘Lineart Vexel’, using pixel-based applications to produce complicated lines to form an image.


Fantasy, Sci-Fi and Thriller

Star Wars Propoganda

Wanted

A great vexel piece of the great thriller/action movie starring Angelina Jolie, ‘Wanted’.

I’m Sorry

Aviatrix

A beautiful vexel piece of a musician called Magdalene Veen. Be sure to click through to view the full size image so you can see the detail in the transition of the different colors.

Clone Trooper

RX78-2

A robotic sci-fi style vexel image. When viewed at full size, this image demonstrates the differences between vector and vexel images well, as you can see the pixels on diagonal lines.

Morrigan

Poison of Live

A warm fiery color palette combined with intricate details make this piece stunning to look at. It was mainly produced in Illustrator, and was finished off using Photoshop to drop it into the vexel category.

Crimson King

Melancholy Journey

A pretty immense, colorful abstract vexel piece by a psychedelic artist known as SaltyShadow.

Hypnos


Nature

Fear La

Fear La uses a lovely varied color scheme and swirly patterns in the ocean to grab the viewers attention. This great piece of vexel art is very powerful and can be interpreted and enjoyed in many different ways!

RUMAHnya KATA

Tree Sunset

Yet another colorful and gorgeous piece, with an abstract watercolor look to it. This is enough to make anyone wish for summer!

Tropical

Sevenlakes

The combination of animals and landscape/scenery in vexel art is quite rare. This piece however, tackles the common problems spectacularly well and gives us, the viewers, something great to look at.

Fisherman’s Vexel

The Sea Tower

This vexel piece makes use of a monochromatic color palette to create a real gloomy and scary mood. The detail of the sky/water and the simplicity of the building creates an interesting combination and is pulled off very well.

Japanese Bridge


People

Xerox

A hilarious washed-out vexel that makes use of texture to add a completely different feel to the design.

Stare Into Me

Lash

An amazing portrait that was completed to improve the artists hair vexeling skills. The pink tones and hair work is just incredible, and it’s hard to imagine how many hours this took!

Can You See Me?

I Can’t Hear You

A much simpler piece of vexel art compared to most others in this showcase, but still very impressive nonetheless!

Key of Heart

Ace of Spades

Yet another beautiful vexel portrait piece, proving that the color combination of greyscale/b&w and red go tremendously well together.

Silence is Golden

Buffy: She’s Like Madonna

This image has so much depth and quality that without close inspection it appears to be a photograph, especially if you’re only glancing!

Hugh Jackman

Hayley Williams

The popular rockstar Hayley Williams in vexel format, another piece that looks just like a photograph, although upon close inspection in full size you’ll notice that it is entirely made up from hundreds of shapes.

Zemotion

Colorful Geisha

This lovely colorful geisha piece of vexel artwork is enough to blow everyone away with the excellent details and shading.

Her Candy World

Cold Ice

Another portrait piece that could easily be mistaken for a glamour photograph.

Hard Candy: Scarlett Johannson

Almost Rainbow

This experimental and very colorful piece is one of the most detailed pieces in this showcase. When viewed at full size (over 1600 pixels wide) you’ll really appreciate the detail, especially the eyes and eyelashes.

The Fooling Around


You May Also Like

Are You An Efficient Early Riser or Energetic Night Owl?

Some would say getting an early start on the day is the best way to go.  You have the opportunity to get focused early on and tackle the day’s tasks and projects with little to no distractions.  Then, when the rest of the world wakes up, you’re already a few hours ahead of the game.

Others profess that tackling the “have to’s” early on in the day allows you to do the “get-to’s” as the day draws to a close.  Many people have had the day to allow ideas and strategies to percolate throughout the day and spend the wee hours making those ideas happen.  In essence, they’re getting a head start as well – just really late the night (or early morning) beforehand.

Then there’s the ever-present question of when you need to be available to others, such as family, friends and colleagues.  That plays into how you tackle your day just as much as anything else.

So, WorkAwesome readers, are you an efficient early riser or do you find you work better as a night owl?  We’d love to hear from you!

Three Quick Snacks That Keep You Productive

If you’re looking for snacks that keep you going – and going in the right direction – during your day, there’s a few choices that will help you “keep your steam” throughout the day.  While there are more out there, here’s three that I keep handy that will get you started:

Almonds
Quick and easy brain food.  Keep these at your desk and you’ve got a healthy – and helpful – snack in the palm of your hands.

Cucumbers
When it comes to the movement of eating alkaline-rich foods, this one is a good starting point.  Acidic foods are said to lower energy and alkaline foods are said to create energy as it keeps us pH balanced.  While you may not be into all that, there’s no doubt that they’re healthy, bite-sized and chock-full of water.

Water
In order to keep moving (both physically and mentally) you need ot be hydrated.  Drink plenty of it and you’ll get plenty done.

Keep these three snacking options at the ready and you’ll be on your way to a more productive day!

Do You Have A Productivity Dilemma?

First things first.

You enjoy what you do…that’s apparent.   That’s why you’re here.  It’s not just your work you enjoy, it’s life in general.  As a matter of fact, you’d love to be able to enjoy all of it more often – completely, even.  That’s always the challenge.  Without a doubt, you can’t have it that way unless you really want it so.  In order to do that, you’ve got to be not only awesome at what you do, but awesomely productive at it.So you’re set on making that happen.  Once you’ve decided that, it leads to the first important question:

“Where do I begin?”

The answer to that one is easy.  You start with a plan.

If you fail to plan, then…

Having a plan in place is paramount when it comes to balancing the act we call “life.”  Our brains just aren’t built to do things effectively and efficiently without a plan in place.  However, deciding to plan is just the first step…it leads to even more questions.

  • What are the most important things to plan for?
  • What order should I prioritize them in?
  • Should I plan everything?
  • How should I organize my planning?
  • No, seriously, should I plan everything?

I’m not going to get into all of those…we’ll explore a lot of that stuff over the course of the next few months.  What I’m going to do is hopefully set you on the path to becoming more productive by answering the question you need to answer yourself first:

“How should I record my planning?”

Not such a simple answer to this question, I’m afraid.  It’s pretty subjective, really.  What it boils down to is how your brain works.  Whatever way works for one person will not work for another.  Bottom line is that you have to choose something.  I’ve touched on this before. While the options are vast, the ways in which you get things down (in order to get things done) fall into three areas:

  • Paper planning
  • Software planning
  • Web planning (the newest of the bunch)

There are pros and cons to each.  Ultimately, it’ll boil down to what you deal with best that will measure your success.

Paper Planning

You don’t need anything fancy (although it does help some to have that structure in place beforehand), you just need something consistent.  There’s something holistic about writing things down on paper to keep on track.  I don’t know if it’s some sort of link from the paper to your brain or if you pay attention more when you’re writing as opposed to typing.  It works for a lot of people, though.

The Pros

  • Very portable
  • Tends to “stick” better
  • Tried and true method

The Cons

  • Not terribly “green”
  • More difficult to file
  • Can cause “electronic redundancy”

Software Planning

Want to be part of the 20th century?  This is the method for you (I say 20th century because there’s another method that’s a tad newer…).  Productivity software is a huge category; there are a lot of choices out there whether you are a Windows, Mac or Linux user.  Many even have a mobile version of their product so that you can take your plans wherever you go.  These programs can store a ton of info and in several different categories without filling your file cabinet.  If you’ve got a lot going on, this may be the way to go.

The Pros

  • Very robust
  • Plenty of choices (so many!)
  • Support available

The Cons

  • Can be very complex and rigid
  • Plenty of choices (too many!)
  • Not necessarily long-lasting

Web Planning

The newest method of planning is done over “the cloud” – or so those who design these new methods would have you do.  The great thing about these is that you have the ability to not bog down your own computer with tasks and to-do lists and can be at computer anywhere and have access to what you need to do.  These systems also have the ability to “sync” with your mobile device as well.  But what if “the cloud” breaks?  Well, you can download your items as well, but then where do you put them?  The latest methods of allowing you to be more productive also raises just as many questions as it professes to provide answers.

The Pros

  • Accessible at any computer
  • (Again) Lots of choices
  • Tends to be more adaptable than proprietary software solutions

The Cons

  • Monthly usage fees (where applicable) can add up
  • (Again) Lots of choices
  • Your data resides on the Internet

The Dilemma Is Yours…

But it doesn’t have to be.  It’s going to be a challenge deciding which way to go when it comes to your all-around planning practices.  I’ll give you some insight on my own methods…which are two-fold.

I’ve been using paper for pretty much all of my life.  I keep going back to it, despite having a ton of productivity tools at my disposal.  However, I can feel a shift coming on as my projects become grander and my freelancing becomes more diversified.  Paper planning is good to keep tabs on thins, but software is far better at handling project planning.  So, I’m likely headed back to electronic productivity methods over the course of the summer…but it will be a gradual shift.

There are two things I’ve learned during my study of productivity over the years.  One is that if you’re going to make a change in how you do things, make sure you do it right.  That, of course, takes planning.  The second thing is to make a change and commit to it.

So whether you decide to commit your plans to paper, software or the web, do one thing for certain…commit all the way.

Simulate Projectile Motion with ActionScript 3.0

In this tutorial I’m going to take you through the process of simulating basic projectile motion using Flash and ActionScript. Our simulation will dynamically animate the initial trajectory of a projectile, and its subsequent bounces against the ground.


The Final Result

Here’s a quick preview of what we’ll be working towards:


Introduction

One of the elements that makes modern video games so realistic is their physics simulation. By applying concepts of classical mechanics to our Flash animations, we can create stunning visual effects that enhance the overall user experience.

In this tutorial I’m going to take you through the process of simulating basic projectile motion using Flash and ActionScript. Our simulation will dynamically animate the initial trajectory of a projectile, and its subsequent bounces against the ground. To keep things simple I have not included air resistance, so the example projectile will only experience one force; gravity. This tutorial assumes you have some basic knowledge of object-oriented programming and ActionScript. You may also benefit from having some experience with quadratic functions, and basic concepts of motion like acceleration and velocity. Although I am mostly going to be covering the application of these concepts as they apply to Flash and ActionScript, I want to first take some time to briefly explain them as they apply to classical mechanics.

Classical mechanics is the branch of physics based on Newton’s laws of motion. In this tutorial we’re going to look at two concepts of classical mechanics: projectile motion, and the coefficient of restitution. Projectile motion describes the path (trajectory) of an object with an initial velocity, while experiencing acceleration from gravity (and in most cases air resistance). You’re probably familiar with the story of Newton formulating his theory of gravity while sitting under an apple tree. Gravity plays a big role in projectile motion, since it adds a constant acceleration of -9.8 m/s2 in the y-direction.

A good example of projectile motion is a baseball being thrown in the air. When you throw a baseball, it has an initial speed and direction at the instant it leaves your hand. These two properties make up the ball’s initial velocity. After the ball leaves your hand, it follows an arc shaped path, also known as its trajectory. The general trajectory of a projectile can be described by a quadratic function:

Position Function

This function gives us the position of a projectile with respect to time (d(t) is the position after t seconds have passed). The little triangle means “change in”, so ?t means “number of seconds passed”.

To use this function we need to know:

  • The acceleration, a, of the projectile;
  • The initial velocity (speed in a particular direction), v1, of the projectile;
  • The initial position, d1, of the projectile.

The path of a projectile in the x and y directions are independent. This means that in order to calculate the position in a 2-dimensional space, we need to use the function twice.

The other concept we’re going to be looking at is something called the coefficient of restitution. The coefficient of restitution is a ratio for describing the difference in an object’s velocity before and after a collision.

For example, if you bounce a basketball against the floor, the height it bounces decreases with each subsequent bounce. This change in height (directly related to the change in velocity), is constant, and can therefore be described by the coefficient of restitution. Calculating the coefficient of restitution for a moving object and a stationary surface is simple:

Coefficient of Restitution

Here, v1 is the velocity of the ball just before it hits the ground, and v2 is the velocity of the ball just after it hits the ground and starts bouncing upwards again.

Since the coefficient of restitution is different for every combination of objects, you will need to find your own, depending on what you are simulating.


Step 1: Setting up the FLA Document

Let’s start building this thing! Open up Flash, and create a new document. In the example I will be using the default dimensions of 550 x 400, and a frame rate of 50 FPS. Save this file under a name of your choice.

Document set-up

Next, we need to create a document class. Create a new Actionscript file, and add the following:

package
{
	import flash.display.MovieClip;

	public class Main extends MovieClip
	{
		public function Main():void{

		}
	}
}

Save this file in the same directory as our FLA. Call it Main.as.

The last thing we need to do is link the document class with the FLA. Inside the FLA, find the Properties panel. Next to Document class, enter the name of the document class, Main.

Document class

For more information about using a document class, please refer to this Quick Tip.


Step 2: Creating the Main Loop

Now that our flash document is set up, we can start coding. The first thing we need to do is create a loop that will run at a fixed time interval. Generally speaking, there are two trains of thought regarding timed loops: using the ENTER_FRAME event, or using the AS3 Timer class. Both methods have different pros and cons, but for this example I am going to use the Timer class.

We need to start by importing two classes: the Timer class, and its respective TimerEvent class. Inside Main.as add the following lines.

import flash.utils.Timer;
import flash.events.TimerEvent;

Before we set up the Timer, I want to add another method called, mainLoop to the document class. As its name suggests, this method will serve as our loop.

public function mainLoop(event:TimerEvent):void{

}

Now we can set up the Timer! We’re going to start by adding two properties to the class: masterTimer, and interval. The masterTimer’s purpose should be obvious, but the interval property will be used to store the length (in seconds) of a Timer interval.

public var masterTimer:Timer;
public var interval:Number;

Next we’re going to populate these properties inside our constructor method, Main. In Step 1 we set our document’s frame rate to 50 FPS. This frame rate can be referenced with stage.frameRate, and will be used as the basis of calculating the Timer interval.

// Get the document's frame rate
var fps:int = stage.frameRate;

// The timer interval in seconds
interval = 1/fps;

// Create a new instance of the timer, first parameter requires the interval in milliseconds
masterTimer = new Timer(1000/fps);

The Timer generates a TimerEvent.TIMER event every interval (in our case, 50 times a second, or once every 20 milliseconds). By adding an event listener to the Timer, we can run our mainLoop method every time this event is generated, thus creating our loop.

// Connect our loop method to the timer.
masterTimer.addEventListener(TimerEvent.TIMER, mainLoop);

The only thing remaining is to start the Timer.

// Start the Timer
masterTimer.start();

Step 3: Testing the Main Loop

If we test the movie as is, nothing will happen. Since we want to know if the loop is working, we are going to add a line to the mainLoop method that outputs the amount of time the SWF has been running. By default the Timer can only return the current number of intervals that have passed. Since we already calculated the length of an interval, we simply multiply the two values to get the time. Please note that I am rounding the result to avoid issues with floating point arithmetic.

// Calculate the current time
var currentTime:Number = int((event.target.currentCount * interval) * 1000) / 1000;

If we trace currentTime, we can see the Timer working.

// Test the loop by tracing the current time
trace("Current Time: " + currentTime);

Test the movie. Your output log should look similar to this:

Output log of timer test

Since we know the Timer is working, we can remove the trace statement.


Step 4: Projectile.as Creating the Class

Our next step is to create a class that represents a projectile (the basketball). Create another ActionScript file, and once again add our basic class structure. Save this file as Projectile.as.

package
{
	import flash.display.MovieClip;

	public class Projectile extends MovieClip
	{
		public function Projectile():void{

		}
	}
}

We’re going to start by adding some properties to keep track of the projectile’s characteristics. I will explain the animation specific properties later. The rest you should recognize from the equations at the start of the tutorial.

// Initial Velocity
private var v1X:Number;
private var v1Y:Number;

// Acceleration
private var aX:Number;
private var aY:Number;

// Initial Position
private var d1X:Number;
private var d1Y:Number;

// Animation-specific
private var startTime:Number;
private var moving:Boolean;

Step 5: Projectile.as Convenience Methods

Since this project uses a lot of calculations, it makes sense to write a set of convenience methods for the tedious calculations which will be performed numerous times. Below are six convenience methods that will be referenced throughout the rest of the tutorial.

The first method, solveQuadratic, return the roots of a quadratic function (in standard form: Ax2 + Bx + C; this method will return the value of x) using the quadratic formula.

private function solveQuadratic(a:Number, b:Number, c:Number):Array{
	// Method paramters format: Ax² + Bx + C
	var solution:Array = new Array(2);
	var discriminant:Number = (b * b) - (4 * a * c); // b^2 - 4ac

	solution["root1"] = ((-1 * b) + Math.sqrt(discriminant)) / (2 * a); // (-b + squareroot(b^2 - 4ac)) / 2a
	solution["root2"] = ((-1 * b) - Math.sqrt(discriminant)) / (2 * a); // (-b - squareroot(b^2 - 4ac)) / 2a

	return solution;
}

The second method, getComponents, returns an array with the individual x and y components of a Euclidean vector.

private function getComponents(angleDegrees:Number, magnitude:Number):Array{
	var components:Array = new Array(2);

	// Trig functions require angles in radians (1 radian = PI/180 degrees)
	components["x"] = magnitude * Math.cos(angleDegrees * Math.PI / 180);
	components["y"] = magnitude * Math.sin(angleDegrees * Math.PI / 180);

	return components;
}

The third method, getPosition, will return the position at a given time. We’re using the position formula from the introduction; this is d(t).

private function getPosition(time:Number, acceleration:Number, initialVelocity:Number, initialPosition:Number):Number{
	var position:Number;

	// d(t) = (1/2)*a*(t^2) + v_1*t + d_1
	position = (0.5 * acceleration * time * time) + (initialVelocity * time) + (initialPosition);

	return position;
}

The fourth method, getTimes, is the opposite of getPosition. It returns the time taken for the projectile to reach a given position.

private function getTimes(finalPosition:Number, initialPosition: Number, acceleration:Number, initialVelocity:Number):Array{
	var time:Array;

	// Solve quadratic position function: 0 = (1/2)*a*(t^2) + v_1*t + d1-d2
	time = solveQuadratic(0.5 * acceleration, initialVelocity, initialPosition - finalPosition);

	return time;
}

The fifth method, getVelocity, uses the first derivative of our position function to return the velocity of the projectile at a given time.

private function getVelocity(acceleration:Number, initialVelocity:Number, time:Number):Number{
	var velocity:Number;

	// Velocity function is first derivative of position function: d' = a*t + v1
	velocity = acceleration * time + initialVelocity

	return velocity;
}

The sixth method, getVelocityDirection, returns the direction (angle) of the velocity at a given time. In other words, it returns the direction that the projectile is moving in at a specific instant.

private function getVelocityDirection(accelerationX:Number, accelerationY:Number, initialVelocityX:Number, initialVelocityY:Number, time:Number):Number{
	var angle:Number;

	var velocityX:Number = getVelocity(accelerationX, initialVelocityX, time);
	var velocityY:Number = getVelocity(accelerationY, initialVelocityY, time);

	angle = Math.atan2(velocityY, velocityX) * 180 / Math.PI;

	return angle;
}

Step 6: Projectile.as Initialization Method

In step 4, we added a bunch of properties to the Projectile class. If you noticed, all these properties are private. I did this because we don’t want to access any of them directly. We still need a way to set and preform the necessary calculations on these properties, so we’re going to add an init method to do so.

public function init(velocityDirection:Number, initialVelocity:Number, initialPositionX:Number, initialPositionY:Number, acceleration:Number = 0, accelerationDirection:Number = 0, gravity:Number = -9.8):void{

}

The names of the different parameters should be fairly obvious. The velocityDirection parameter takes the angle of the initialVelocity in degrees. The acceleration parameters are all optional. If you set a value for acceleration, you will need to provide a separate value for accelerationDirection as we did with velocityDirection.

I mentioned earlier that we’re dealing with components, however our init method only accepts a vector (magnitude and direction). This is where our convenience methods come into play.

// Get components for our velocity and acceleration vectors
var vComponents:Array = getComponents(velocityDirection, initialVelocity);
var aComponents:Array = getComponents(accelerationDirection, acceleration);

Now we have an array containing the individual components of the vectors. We can now store them to their corresponding properties.

// Store these vectors in the corresponding properties
v1X = vComponents["x"];
v1Y = vComponents["y"];

aX = aComponents["x"];
aY = aComponents["y"] + gravity; // This is where we add the additional force of gravity in the y-direction

The points for initial position do not need to be changed.

// Store the initial position
d1X = initialPositionX;
d1Y = initialPositionY;

Step 7: Projectile.as Control Methods

Before we continue, I need to explain the animation-specific properties we created in Step 4. I’ll start with the moving property. Since our projectile has a rest state, we use the moving property as a flag so the loop only animates when the projectile is in motion. The startTime property is used to account for the difference between the global time of the Timer, and the local time of the projectile’s position function. Nothing too complicated.

Our control methods, for lack of a better term, will, for the most part, be called from within the loop. These first three methods are really simple, and are used to interact with the animation-specific properties.

public function begin(currentTime:Number):void{
	startTime = currentTime;
	moving = true;
}

public function end():void{
	moving = false;
}

public function isMoving():Boolean{
	return moving;
}

The last method we’re going to add deserves most of our attention. As its name suggests, the positionAtTime method returns the position of the projectile at a given time. We can use this position inside the loop to animate our MovieClip on the stage.

public function positionAtTime(currentTime:Number):Array{
	var relativeTime:Number = int((currentTime - startTime) * 1000) / 1000;
	var position:Array = new Array(2);

	position["x"] = getPosition(relativeTime, aX, v1X, d1X);
	position["y"] = getPosition(relativeTime, aY, v1Y, d1Y);

	return position;
}

If you look inside this method, you should notice a couple of things. This first thing is the use of a relativeTime variable. I mentioned earlier that we need to account for the difference in time between the Timer and Projectile. The beginning of the projectile’s trajectory starts at a relative time of 0, so we’re only interested in the the amount of time that has passed on the Timer since this trajectory began. This is why we store the startTime. The second thing is the use of our getPosition method from step 5. We use this method twice to calculate the position of the Projectile in both axes.

Save the Projectile class.


Step 8: Projectile.as Linking to a MovieClip

Before we can animate, we need something to animate. If you noticed, our Projectile class extends the MovieClip class, which means we can link it to a MovieClip in our library.

Open the main flash document (the FLA), and draw a circle on the stage. Don’t worry too much about the size, since we’re going to scale it down later in code.

Create circle

Next, convert the circle to a MovieClip. The MovieClip should appear in your library, once it does, delete it from the stage since we will be adding it programmatically in the next step.

Now we need to link our Projectile class with the MovieClip. In your library right click (Control click on the Mac) your MovieClip and select Linkage…

Select linkage...

Check the box beside Export for ActionScript. Enter Ball for Class, and Projectile for Base class.

Linkage...

Click OK. You may see a dialogue box telling you that a class definition could not be found, and that one will be generated automatically. Click OK again.

Class not found

Finally, save the document.


Step 9: Animating!

We have a loop, we’ve written our Projectile class, and we’ve linked it with a MovieClip. Now it’s time to animate the projectile! To begin, open our document class, Main.as.

We’re gonna start by adding a few more properties.

public var scale:int;
public var ball:Ball;
public var startFlag:Boolean;

The purpose of these properties is pretty straightforward. The scale property is going to represent a scale between Flash’s pixel position and our calculated metre position. The ball property represents the MovieClip we created in the previous step. You might notice that its type is set to Ball, this is the class name we set in the previous step. Finally the startFlag property is used as a flag to tell the loop when our projectile should begin its trajectory.

Inside the constructor method, we’re going to add the following lines to setup our Ball object.

// 1 metre = "scale" pixels
scale = 100;	//i.e. 100 pixels = one metre, 1 pixel = 1cm

// Create a new instance of the Ball
ball = new Ball();

// Set the size of the ball, in this case it's 0.5m x 0.5m
ball.height = 0.5 * scale;
ball.width = 0.5 * scale;

// Position the ball on the stage
ball.x = 50;
ball.y = 350;

// Add the ball to the stage
stage.addChild(ball);

If you test the movie, your ball should appear in the bottom-left corner of the stage.

Add ball to stage

Next we need to run the init method from step 6. If you look at the method declaration, you’ll see that it requires a minimum of 4 paramters: velocityDirection, initialVelocity, initialPositionX, and initialPositionY. Staying in the constructor method, let’s set those up!

// Run the projectile init method to set the properties of our projectile
ball.init(80, 7, ball.x / scale, (stage.stageHeight - ball.y) / scale);

The parameters for initial position require some simple calculations before they’re passed on to the method. The Projectile methods all use metres as the unit of distance, so we need to use our scale. The initialPositionY requires an additional step. Since Flash’s origin exists in the top-left corner, and increasing y moves down the screen, we need to subtract our y-position from the stage.stageHeight, to move our origin to the bottom-left and allow increasing y to move up the screen.

Now that our projectile is configured, we can set the startFlag.

// Set the starting flag, so the loop puts the ball in motion
startFlag = true;

Let’s move on to setting up the loop. The first thing we need to do is add a conditional statement that checks for the startFlag.

// Start motion if the flag has been flagged
if(startFlag == true){
	ball.begin(currentTime);
	startFlag = false;
}

There’s a few things worth noting. If you recall, we already created a variable called currentTime in Step 3. Also, since we only want to call the begin method once, we set the startFlag property back to false.

It would be pointless for the loop to calculate the position of the projectile if it’s at rest, so we need to add another conditional statement that checks whether the projectile is moving.

// Animate if ball is in motion
if(ball.isMoving() == true){

}

Inside this statement we can implement the actual animation. The first thing we need to do is get the projectile’s position.

// Get the current position
var currentPosition:Array = ball.positionAtTime(currentTime);

Once we know the position, we simply update the MovieClip’s position. Similar to the init method, we need to take into account our scale, and Flash’s origin.

// Move our custom MovieClip
ball.x = currentPosition["x"] * scale;
ball.y = stage.stageHeight - currentPosition["y"] * scale;

We’ve finally reached a milestone! If you test the movie now, you can see the basic effect!


Step 10: Making the Ball Bounce

We’ve animated the trajectory of our projectile, but as you can see the ball keeps moving indefinitely. To enhance this simulation, we’re going to create a ground on which the ball can bounce. For simplicity’s sake, we’re going to make our ground an imaginary line, at the bottom of the stage.

Our approach here involves implementing collision detection. Generally speaking we have two options for our collision detection: frame-based and predictive. Ultimately we are going to be using predicative collision detection, but I think its worth explaining the theory behind each option:

The idea behind frame-based collision detection is simple. Inside the loop, we would check whether the ball’s y-position is below the ground’s y-position. If the condition is met, a collision has taken place…sounds good right? Not really. Chances are that a collision will not happen on an exact Timer interval. This means that the time and position of the bounce will be inaccurate. Consider this diagram:

Example of problem with frame-based collision detection

The actual collision would have taken place in between the two frames. But our frame-based collision detection code would only have detected the collision in the second frame, when the projectile should already be on its new trajectory.

We can overcome this problem by using predictive collision detection. It can be slightly more challenging to implement, but it gives us a more accurate simulation. Predictive collision detection works as follows. We first calculate, in advance, the exact time that the projectile will collide with the ground. Inside the loop we check whether this time has passed. If it has, we set the projectile on a new trajectory, starting at that exact time of collision.

First thing’s first, we need to add a few more methods to our Projectile class. We’ll start with timeOfCollision.

public function timeOfCollision(ground:Number):Number{
	var time:Number;
	var times:Array;

	times = getTimes(ground, d1Y, aY, v1Y);

	// We don't want the negative time result, so use the larger time
	time = Math.max(times["root1"], times["root2"]);

	// We need to consider the startTime as well since we're checking the loop
	time = time + startTime

	return time;
}

(Remember, getTimes returns the time at which the projectile will be at a specified position. It will actually return two times, one negative and one positive, because these are the roots of a quadratic equation.)

We’re also going to need to know the magnitude and direction of our velocity at this time, so add these two methods for calculating that as well.

public function velocityAtTime(currentTime:Number):Number{
	var relativeTime:Number = int((currentTime - startTime) * 1000) / 1000;

	var velocity:Number;

	var velocityX:Number = getVelocity(aX, v1X, relativeTime);
	var velocityY:Number = getVelocity(aY, v1Y, relativeTime);

	// Pythagorean theorem
	velocity = Math.sqrt(velocityX * velocityX + velocityY * velocityY);

	return velocity;
}

public function velocityDirectionAtTime(currentTime:Number):Number{
	var relativeTime:Number = int((currentTime - startTime) * 1000) / 1000;

	var angle:Number;

	angle = getVelocityDirection(aX, aY, v1X, v1Y, relativeTime);

	return angle;
}

Before we finish up with this class, I want to add one more method called getStartTime. We will be using it in the next step.

public function getStartTime():Number{
	return startTime;
}

Save the Projectile class and return to the document class. The first thing we need to do is add a couple of properties. A collisionTime property, and a cor property to represent our coefficient of restitution.

public var collisionTime:Number;
public var cor:Number;

The first thing we need to do is set our cor. We can set this in the constructor method. I’ve picked 0.8, but feel free to experiment with different values to see the effects.

// Set the coefficient of restitution. Must be a value between 0 and 1
cor = 0.8;

Now for the fun part! Inside our main loop, we need to implement our bouncing methods. For starters, find the condition for startFlag. Inside add the following line. This will calculate our initial collision time.

// Since the position is the centre point of the ball, the y-position of the ground is actually at half the height of the ball.
collisionTime = ball.timeOfCollision((ball.height / 2) / scale);

Next find the condition that checks ball.isMoving(). We’re only going to check for collisions if the ball is in motion, so we’ll put our collision detection statements in there. Add the following to the top of the condition.

// Check if a collision happened
if(currentTime >= collisionTime){

}

Inside that collision condition, we need to execute the bounce. We achieve this by setting the projectile on a new trajectory, starting at collisionTime. The first thing we need to do is calculate the direction and magnitude of the velocity at collisionTime.

var newVelocityDirection:Number = -1 * ball.velocityDirectionAtTime(collisionTime);
var newVelocity: Number = ball.velocityAtTime(collisionTime) * cor;

Next we need to run the appropriate methods for setting the new trajectory. For the timeOfCollision method, we need to set our ground y-position to half the height of the ball. We do this because the y-position of the ball is actually at its centre point, not its base.

// Set the new trajectory
ball.init(newVelocityDirection, newVelocity, ball.x / scale, (stage.stageHeight - ball.y) / scale);
ball.begin(collisionTime);
collisionTime = ball.timeOfCollision((ball.height / 2) / scale);

We’ve reached another milestone! If you test the movie, you should see the bouncing effect.


Step 11: But the Bouncing Never Stops!

If you take a look at the above example, the ball never comes to a complete stop. Towards the end it appears to have a quick, jittery motion. This phenomenon is caused by the following line:

var newVelocity: Number = ball.velocityAtTime(collisionTime) * cor;

I’ll explain. Assuming cor is not equal to 0 or 1, our projectile’s velocity will only approach zero, getting slower and slower, but never actually reaching it. Since the reality is that our projectile does come to rest, we need to implement a solution for this problem.

Here’s how. Since the cor is constant, we can look at the bounces as a geometric series:

  • a1: Time taken for first bounce
  • a2: Time taken for second bounce
  • a3: Time taken for third bounce

Each a term in the sequence represents the length of time for a bounce. We then refer to the cumulative time taken like so:

  • S1: Time taken for first bounce
  • S2: Time taken for first bounce and second bounce
  • S3: Time taken for the three first bounces, in total

From here, we can use the formula for the sum of an infinite geometric series to calculate our stopping time:

Formula for sum of an infinite geometric series

The formula itself is simple. The a1 variable, represents the first term in the series, in our case, the length of the first bounce. The r variable represents the series’ ratio, in our case, the cor.

As far as the implementation goes, we’ll start by adding two more properties to the document class.

public var stoppingTime:Number;
public var bounce:int;

We need to know when the first bounce occurs, so the bounce property will be used as a simple counter. Inside the loop’s startFlag condition (this if-statement: if(startFlag == true){) add the following after our declaration of cor:

// Reset the bounce count
bounce = 0;

Next, add the following to the end of our collision condition.

// Increase number of bounces
bounce++;

// Calculate stopping time on first bounce
if(bounce == 1){
	// Sum of infinite geometric series: S = a_1 / 1 - r
	stoppingTime = (collisionTime - ball.getStartTime()) / (1 - cor) + ball.getStartTime();
}

Every time a collision occurs we need to check whether stoppingTime has passed. If it has we can bring the projectile to rest, by calling the end method. The loop is still going to reposition the ball one last time, so we need to set the ball to its correct final position. The loop already set the projectile on a new trajectory, so we’re going to get around this by setting currentTime to ball.getStartTime().

// If we reach the stopping time, end the motion
if(bounce > 1 && collisionTime > stoppingTime){
	ball.end();

	// Since the ball is already on a new trajectory, force it to its start position
	currentTime = ball.getStartTime();
}

That’s it! The projectile now bounces and comes to a complete stop.


Step 12: Adding Basic UI Control

When we play the movie, the projectile fires immediately. This is pretty useless for most applications, so let’s change things a bit and add some basic UI controls. To keep things simple, we’re going to add two buttons: a start button, and a reset button.

Our first step is similar to Step 8. In the FLA document, draw two buttons for Start and Reset. Convert each button to a symbol, this time make them Buttons as opposed to MovieClips. This time we are going to keep our buttons on the stage, so position them as desired. Similarly to Step 8, open the Linkage Properties for one of the buttons. Check the box beside Export for ActionScript, this time however, leave the default class names. Click OK and repeat this for the other button.

Linkage properties for the buttons

On the stage, select the Start button. Open up the Properties panel. Where it says <Instance Name> enter startButton. Repeat this for the reset button, calling it resetButton.

Enter the instance name

Save this file, and open the document class. Inside, we need to import the MouseEvent class.

import flash.events.MouseEvent;

Inside the constructor method remove the following lines.

// Run the projectile init method to set the properties of our projectile
ball.init(85, 6, ball.x / scale, (stage.stageHeight - ball.y) / scale);

// Set the starting flag, so the loop set's the ball in motion
startFlag = true;

We’re going to replace this by adding event listeners for each of the buttons we created. Notice that we can reference them with the <Instance Name> we set earlier.

// Add event listeners for our start and reset buttons
startButton.addEventListener(MouseEvent.CLICK, startEvent);
resetButton.addEventListener(MouseEvent.CLICK, resetEvent);

Finally, we can wrap everything up by adding the two methods we’re calling from those event listeners.

public function startEvent(event:MouseEvent):void{
	// Don't start if its already in motion
	if(ball.isMoving() == false){
		// Run the projectile init method to set the properties of our projectile
		ball.init(85, 6, ball.x / scale, (stage.stageHeight - ball.y) / scale);

		// Set the starting flag, so the loop set's the ball in motion
		startFlag = true;
	}
}

public function resetEvent(event:MouseEvent):void{
	// End the motion
	ball.end();

	// Move ball back to original position
	ball.x = 50;
	ball.y = 350;
}

The Final Result


Conclusion

Although the final result is simple, it works, and it shows how easy it is to implement real, dynamic physics concepts into your flash projects. How you choose to apply them comes down to your own creativity. If you’re looking for a more complete, intuitive solution, it might make more sense to check out an existing physics engine like QuickBox2D.

To summarize: we’ve created a timed loop, written a class that models the trajectory of a projectile and added the necessary collision detection to simulate bounce. We covered a lot of content, but ultimately, we’ve barely scratched the surface of what we can do with classical mechanics. In projectile motion alone, there is still room to add things like drag, air resistance, and terminal velocity.

I hope you have enjoyed this tutorial. Thanks for reading!

10 Django Trouble Spots for Beginners


Django is an incredibly-powerful web framework, but using it can be a bit daunting for new users. I found this out the hard way over a year ago, spending hours struggling with even the most basic of concepts. If you're new to Django, (or MVC frameworks in general), you're probably going to have to shift your thinking a bit to use this robust framework. Here are some of the issues that I had to struggle with before I fully understood them. Hopefully, this will save you hours of struggling.


1. It's Not a CMS

Django isn't a CMS. It can't do everything that WordPress or Drupal can do right out of the box. That said, you can do infinitely more with Django, because it isn't a CMS.

If you have a background with, for example, a platform like WordPress, it's going to take a while to wrap your head around the fact that you're going to have to do a lot more things manually, such as creating urls or modifying settings. Most of the configurations won't be done in a UI, but instead with Python files.

While Django does come with a pretty nifty admin area straight out of the box, configuring Django sometimes isn't as easy as a standard CMS.


2. Local Environment Setup

One of the biggest initial hurdles that new users face is configuring their local environment for Django. For many beginners, it takes longer to install the framework locally than to build their first app. PHP frameworks like CakePHP are pretty much ready to start using once you've downloaded them on your local machine.

Installing Django and configuring it to run on the local machine can be kind of tricky, especially if you're not familiar with concepts like symlinks. The Django install docs are pretty comprehensive, but if those don't work for you search for some video instruction or platform-specific documentation.


3. Projects vs. Apps

If you're new to Django (or MVC frameworks in general), odds are the terms "projects" and "apps" might be a little confusing.

With Django, a Project is just a collection of apps. Say you were building a YouTube clone; you would create a project, "MyTube", that would contain apps like "videos", "comments", "ratings", "blog", etc.

Apps are similar to modules in a CMS, except you build them from scratch. They're a lot smaller in scope, typically performing only one main function. For the MyTube example, you wouldn't just create one app that allowed users to upload videos, comment on them, rate them, and anything else. You want your apps to be small in scope, performing only one or two functions by themselves.


4. Template Inheritance

Template inheritance is one of the best features of Django, but it usually takes a while to truly understand.

With a traditional CMS, you might split reusable parts of a template out into their own files (like a header file), and include them in each of the templates. With Django, you create a base.html template, and you specify blocks that can be overwritten in child templates. This keeps your code more reusable.

So, for an example, you might have a base.html template that has this:

<div>
  {% block content %}
    <p>Here is our content that will be overwritten</p>
  {% endblock %}
  <p>Other stuff that won't be overwritten.</p>
</div>

Then in another template you may choose to overwrite the {% content %} block. Instead of having to include a sidebar file into the design, we just simply do something like this:

{% extends base.html %}

{% block content %}
I'd like a different content block!
{% endblock %}

This extends the base.html. This method allows you finer control over your templates, and ensures that you're not creating duplicate code.

To learn more about the power of template inheritance, check out this article on the power of Django template inheritance.


5. Separation of Code and Media Files

Because Django doesn't serve media files itself, it likes to separate the media files (images, JavaScripts, stylesheets, etc. ) into a directory away from the apps. This allows you to decide how you're going to serve those static files. You could use a separate webserver or cloud services like Amazon S3 to serve the files.

Your project files might look something like this:

MyProject
  - app
  - app2
  - media
    - javascript
    - stylesheets
    - images
  ....

6. Migrations

Database migrations are a trouble-spot for many beginners. This happens when you already have fields in your database (production or development), and you add something that modifies the database.

Other frameworks like Rails have database migrations built in. With Django, however, unless you use a third-party solution, you have to do the migrations by hand. Fortunately, there is an excellent third-party tool that handles Django migrations: South.

South allows you to perform database migrations, much like Rails allows, and is easy to roll into your existing project. It's powerful and simple, and takes care of the issue of database migrations that Django has. Here's a tutorial that has examples of how South works.


7. Local vs. Production Environments

Django comes with sqlite, a simple flat-file database that doesn't need any configuration. This makes prototyping fast and easy right out of the box.

However, once you've moved your project into a production environment, odds are you'll have to use a more robust database like Postgresql or MySQL. This means that you're going to have two separate environments: production and development.

Django doesn't really have logic baked in that allows you to easily switch between two different settings without manually editing the settings.py file. For example, having the setting

DEBUG = True

is helpful for local environments, because it provides helpful error messages when code goes bad. But if you're on a production environment, you'll never want users to see your error messages, so you'd need to specify –

DEBUG = False

.

There is a way to automatically toggle between the two environments, using this quick modification:

  import socket

  if socket.gethostname() == '<a href="http://productionserver.com" target="_blank">productionserver.com</a>':
      DEBUG = False
  else:
      DEBUG = True

You can reuse the socket bit in different areas of your settings.py as well.


8. Writing Custom Template Tags

Template tags are an insanely useful aspect of Django. In fact, it ships with many built-in template tags right out of the box.

However, if you're wanting to write your own custom template tags, it can get a bit tricky. Here's a simple example of writing a custom template tag that should give you a better understanding of how template tags work and how to create your own.


9. Django User Authentication

Django comes with a great user authentication system in the project admin that you can use to manage users. However, the user authentication system doesn't provide a simple way to allow non-admins to create user accounts. CMSs, like Drupal, handle this beautifully right out of the box.

There are a few great options for public user authentication systems that provide this missing functionality. The most popular third-party solution is probably django-registration. It's simple yet flexible, and provides everything you need to get user signups in your application.


10. Generic Views

Generic views are incredibly powerful, and can save you a lot of time writing views for your Django app. However, most beginners don't know how useful and powerful they are.

For example, if you want to create a flat page for your homepage, but want to style it differently, you can create a template in your flatpages template directory that utilizes the direct_to_template view.

Aside from creating the proper template, you'll need to modify your urls.py file to point to it:

urlpatterns = patterns('',
  (r'^$', 'django.views.generic.simple.<WBR>direct_to_template', {'template': 'homepage.html'}),
.....

Now, we have a homepage with a custom design that doesn’t require writing any custom views. I’ve utilized this technique many times instead of writing extra views.


Conclusion

Once you've worked through all the tricky areas that catch most beginners, Django will prove to be a really fast and powerful tool for building web applications. Don't get discouraged if you find yourself confused early on. You can always find help within the Django IRC channel; Stackoverflow is another excellent place to ask questions.

10 Django Troublespots for Beginners


Django is an incredibly-powerful web framework, but using it can be a bit daunting for new users. I found this out the hard way over a year ago, spending hours struggling with some of the basic concepts of Django. Today, it's the only thing I use to develop custom sites and applications – though getting started required a bit of a learning curve.

If you're new to Django, (or MVC frameworks in general), you're probably going to have to shift your thinking a bit to use this robust framework. Here are some of the issues that I had to struggle with before I fully understood them. Hopefully, this will save you hours of struggling.


1. It's Not a CMS

Django isn't a CMS. It can't do everything that WordPress or Drupal can do right out of the box. That said, you can do infinitely more with Django, because it isn't a CMS.

If you have a background with, for example, a platform like WordPress, it's going to take a while to wrap your head around the fact that you're going to have to do a lot more things manually, such as creating urls or modifying settings. Most of the configurations won't be done in a UI, but instead with Python files.

While Django does come with a pretty nifty admin area straight out of the box, configuring Django sometimes isn't as easy as a standard CMS.


2. Local Environment Setup

One of the biggest initial hurdles that new users face is configuring their local environment for Django. For many beginners, it takes longer to install the framework locally than to build their first app. PHP frameworks like CakePHP are pretty much ready to start using once you've downloaded them on your local machine.

Installing Django and configuring it to run on the local machine can be kind of tricky, especially if you're not familiar with concepts like symlinks. The Django install docs are pretty comprehensive, but if those don't work for you search for some video instruction or platform-specific documentation.


3. Projects vs. Apps

If you're new to Django (or MVC frameworks in general), odds are the terms "projects" and "apps" might be a little confusing.

With Django, a Project is just a collection of apps. Say you were building a YouTube clone; you would create a project, "MyTube", that would contain apps like "videos", "comments", "ratings", "blog", etc.

Apps are similar to modules in a CMS, except you build them from scratch. They're a lot smaller in scope, typically performing only one main function. For the MyTube example, you wouldn't just create one app that allowed users to upload videos, comment on them, rate them, and anything else. You want your apps to be small in scope, performing only one or two functions by themselves.


4. Template Inheritance

Template inheritance is one of the best features of Django, but it usually takes a while to truly understand.

With a traditional CMS, you might split reusable parts of a template out into their own files (like a header file), and include them in each of the templates. With Django, you create a base.html template, and you specify blocks that can be overwritten in child templates. This keeps your code more reusable.

So, for an example, you might have a base.html template that has this:

<div>
  {% block content %}
    <p>Here is our content that will be overwritten</p>
  {% endblock %}
  <p>Other stuff that won't be overwritten.</p>
</div>

Then in another template you may choose to overwrite the {% content %} block. Instead of having to include a sidebar file into the design, we just simply do something like this:

{% extends base.html %}

{% block content %}
I'd like a different content block!
{% endblock %}

This extends the base.html. This method allows you finer control over your templates, and ensures that you're not creating duplicate code.

To learn more about the power of template inheritance, check out this article on the power of Django template inheritance.


5. Separation of Code and Media Files

Because Django doesn't serve media files itself, it likes to separate the media files (images, JavaScripts, stylesheets, etc. ) into a directory away from the apps. This allows you to decide how you're going to serve those static files. You could use a separate webserver or cloud services like Amazon S3 to serve the files.

Your project files might look something like this:

MyProject
  - app
  - app2
  - media
    - javascript
    - stylesheets
    - images
  ....

6. Migrations

Database migrations are a trouble-spot for many beginners. This happens when you already have fields in your database (production or development), and you add something that modifies the database.

Other frameworks like Rails have database migrations built in. With Django, however, unless you use a third-party solution, you have to do the migrations by hand. Fortunately, there is an excellent third-party tool that handles Django migrations: South.

South allows you to perform database migrations, much like Rails allows, and is easy to roll into your existing project. It's powerful and simple, and takes care of the issue of database migrations that Django has. Here's a tutorial that has examples of how South works.


7. Local vs. Production Environments

Django comes with sqlite, a simple flat-file database that doesn't need any configuration. This makes prototyping fast and easy right out of the box.

However, once you've moved your project into a production environment, odds are you'll have to use a more robust database like Postgresql or MySQL. This means that you're going to have two separate environments: production and development.

Django doesn't really have logic baked in that allows you to easily switch between two different settings without manually editing the settings.py file. For example, having the setting

DEBUG = True

is helpful for local environments, because it provides helpful error messages when code goes bad. But if you're on a production environment, you'll never want users to see your error messages, so you'd need to specify –

DEBUG = False

.

There is a way to automatically toggle between the two environments, using this quick modification:

  import socket

  if socket.gethostname() == '<a href="http://productionserver.com" target="_blank">productionserver.com</a>':
      DEBUG = False
  else:
      DEBUG = True

You can reuse the socket bit in different areas of your settings.py as well.


8. Writing Custom Template Tags

Template tags are an insanely useful aspect of Django. In fact, it ships with many built-in template tags right out of the box.

However, if you're wanting to write your own custom template tags, it can get a bit tricky. Here's a simple example of writing a custom template tag that should give you a better understanding of how template tags work and how to create your own.


9. Django User Authentication

Django comes with a great user authentication system in the project admin that you can use to manage users. However, the user authentication system doesn't provide a simple way to allow non-admins to create user accounts. CMSs, like Drupal, handle this beautifully right out of the box.

There are a few great options for public user authentication systems that provide this missing functionality. The most popular third-party solution is probably django-registration. It's simple yet flexible, and provides everything you need to get user signups in your application.


10. Generic Views

Generic views are incredibly powerful, and can save you a lot of time writing views for your Django app. However, most beginners don't know how useful and powerful they are.

For example, if you want to create a flat page for your homepage, but want to style it differently, you can create a template in your flatpages template directory that utilizes the direct_to_template view.

Aside from creating the proper template, you'll need to modify your urls.py file to point to it:

urlpatterns = patterns('',
  (r'^$', 'django.views.generic.simple.<WBR>direct_to_template', {'template': 'homepage.html'}),
.....

Now, we have a homepage with a custom design that doesn’t require writing any custom views. I’ve utilized this technique many times instead of writing extra views.


Conclusion

Once you've worked through all the tricky areas that catch most beginners, Django will prove to be a really fast and powerful tool for building web applications. Don't get discouraged if you find yourself confused early on. You can always find help within the Django IRC channel; Stackoverflow is another excellent place to ask questions.