Colors are produced by the movement of metal ions when introduced to flame. Heat from the flame excites the ions, and as the ions move, they release a burst of light energy.
When an ion is excited, the electrons are moved to a higher energy state. This state is also unstable and cannot be sustained for long, and so the ions will fall back to the original state. The jumps between energy states produce a light, and the differences in the size of the movements between metals is reflected in the different colors seen.
The amount of energy produced by an ion as it moves depends on the metal. This then affects the color produced. A flame test can be used to detect which metals are in a compound. For instance, lithium produces a red flame, while barium produces a pale green flame.