Guns, gunpowder, and firearms have been around for quite some time. Gunpowder first showed its face in China around the 9th century, then spread to the Middle East, and Eastern Europe until finally reaching Western Europe sometime after the Crusades. Firearms have existed in some form as well, ever since China invented the hand cannon — a handheld (but heavy) gunpowder-filled tube — in 1232. And in 1364, we have the first recorded use of shooter-lit wicks by hand that ignited gunpowder that was loaded into a gun barrel - the matchlock arquebus. So guns actually had a place in the medieval world and are not a purely modern phenomenon. So why do Fantasy fiction and RPG developers treat it like a Red-Headed Stepchild? In their worlds, guns don't exist. Cannons maybe, gunpowder possibly, rockets if they're having a good day... but no guns.
There are three main issues tied with this trope. Mix and match troopers. It's frequently attributed to the assumption that guns ended the era of knights; while it might be that creators of works of fantasy think this, the assumption itself isn't true. Guns and knights existed side-by-side for over 300 years. After the advent of guns blacksmiths would deliberately shoot at their armour — and customers would look for the dent, because it indicated that the armour would stop bullets. That's the origin of the term 'bullet proof' — the armour was proofed (tested) against bullets. Early guns were not superior to traditional projectile weapons in every respect. They were more like crossbows, point-and-trigger (minimal training requirement) weapons with low rate of fire (and initially used a trigger mechanism borrowed from them). In fact, an English officer seriously suggested in the late 18th century (i.e. around the time of The American Revolution) that the Redcoats go back to the longbow, for the improved rate of fire. He was ignored, of course; he had forgotten about the training issue... although the English had still been using longbows as late as the Thirty Years' War, causing enough deforestation that one of the reasons they switched was because there was hardly a yew tree left in Europe anymore. The real change in warfare was the Swiss introduction of pikes in the 15th and 16th centuries — much like the Greek phalanxes, but the Swiss were much more known for charging with them. They were first stopped by the fittingly-named Francis I of France, who used field fortifications — and musketeers. Knightly charges had been showing vulnerabilities for some time before this happened, though. They were a widespread tactic in Medieval age as it was a long established tradition dating back to when Frankish and Anglo Saxon chiefs/kings would smash poorly equipped infantry whilst on horseback surrounded by trusted warriors. Although some nations still maintained effective disciplined infantry (Anglo-Saxon England, for one, and the core of it was kept intact by the Normans), it generally required a large body of professional soldiery that didn't exist. Although cavalry had long proved their worth, and was easily provided by the feudal/manorial social system of the time, cracks appeared by the 'High' Middle Ages. They were only dubiously useful in the Crusades (11th through 14th Centuries), and useless against the Mongols, as both the Mongols and the Turks used light cavalry and didn't field solid ranks of troops. Longbows had difficulty penetrating plate armor (the difficulty dependent on the bow and armor), contrary to popular belief, but Crécy and Agincourt did reveal further problems — at Crécy (1346), the French lost because their horses had no barding armor, and so had no protection against arrows, but at Agincourt (1415), they lost because they did have barding armor, and so got stuck in the mud. Yet worse were the introduction of very literal Panzerkampfwagens in the Hussite Rebellion (1415-1436) — the Bohemians (modern Czech Republic and Slovakia) invented the wagon circle to defend against Hapsburg knights, and attacked with massed wagons carrying light cannon and ten or twelve peasants with flails. They won, by the way; moderate Hussites had religious freedom in Bohemia until the Thirty Years' War (when they got caught up in the Catholic-Protestant wars that had begun with the Smalkaldic War of 1525 and were annihilated). So, in short, knightly charges were dead without needing firearms to kill them. Personal firearms (including cavalry pistols) were if anything more useful in countering the new styles of heavy infantry; before long, though, the musket meant the conversion of knights into cavalry (not necessarily noble, and taking orders from the general rather than acting largely on their own), and the relegation of pikes to uselessness except in defending against cavalry attack. (The Janissaries managed to fight with musketeers without using any pikemen at all.) Although plate armour was worn up till the middle of the 17th century, improvements that led to increased muzzle velocity and higher bullet calibre rendered it pointless to have without making it thicker and heavier, which was just not practical. That's why you see pictures of 17th century troops in metal breastplates and helmets, whilst by the 18th they'd abandoned them, though the garish colours and tricorne hats are quite spiffing. Breastplates and helmets wouldn't return until World War I, when the sheer quantity of shrapnel put out by modern artillery (plus the technique of indirect fire that allows one to deliver said shrapnel even if you can't see where the shell will land) brought both back (often based on medieval designs; compare the kettle hat to the Brodie and Adrian helmets or the sallet to the iconic Stahlhelm). The use of mixed pikes and firearms (pike-and-shot) continued for quite a long time, but by the end of the 17th century the arrangement had more or less disappeared. The reason was the widespread adoption of an innovation that came from (according to legend) an ingenious blacksmith of Bayonne, France, who realized that a gun was basically a pike-staff that could shoot bullets. Attach a blade to the end of a gun (called a bayonet to this day), and voila! you have a serviceable spear. After some problems - like how to remove a blade that you inadvertently jammed in your gun - were ironed out, bayonets were more or less standard issue in European arsenals. They still remain in use today, though more as a utility knife and a training tool for aggression. Never bring a gun to a sword fight. Of course, there are also dramatic reasons for this trope.
"By Heracles, this is the end of man's valour!"As cool as gun fights can be, they just can't accomplish the level of intensity of a one-on-one duel with swords. If a hero has a gun, he can just shoot the villain from afar. But with swords, they can get up close and personal, engage in witty banter, look each other in the eye, and, if one gets that fatal cut or thrust in, engage in the drama of watching the other die. This is why even modern-day Action Movies will often have their final showdown be a hand to hand confrontation between the hero and the villain rather than a gun fight. The reason may also be that guns are too modern. They're the primary weapon of choice in the real world. If fantasy authors want to achieve that escapist, ancient feel in their story, they have to use ancient weapons. Guns don't have that level of romance. This could also be the reason why Automatic Crossbows are excused despite being functionally similar to guns. There is also the widespread perception that guns take all the "skill" or "honor" out of fighting and make the heroes look cheaper: no intensive training with ancient masters, just "BANG! He's dead." One is only left to wonder if some long time in the future, where they fight with yet-unimaginable weapons, it's going to be guns that carry the "oldie but goodie" flavor of cold steel in today's fiction. Ready, aim... fireball! May or may not be justified in Magitek settings. Why bother with explosives when you can blow somebody up with a fireball? Because anyone can use a gun, but not everyone can throw fireballs. This is a common issue of technology versus magic: technology works for people who haven't spent years studying the sacred mysteries. (The same problem exists for longbows.) But if the magic trinket can be activated by anyone, why bother with explosives when you can blow somebody up with a fireball from a wand? 'Point, say the command' is just as simple as 'point, pull the trigger' assuming a wand doesn't just need a thought to activate which in itself is advantageous. With greater power and availability of magic this becomes less and less of a problem. In other words why bother with a gun that's heavy, has limited ammunition and chances of jamming when you can use a little inconspicuous stick that has limitless shots and can be used for a variety of functions aside from killing. Especially true if the setting can have small wands or similar magical trinkets capable of mass destruction. The same can't always be said of guns unless they're some kind of Magitek. This is the reason that, for the most part, guns aren't used in the Eberron setting of D&D (although they do exist).
—King Archidamus of Sparta (IV century B.C.), according to Plutarch, on seeing the missile shot by a catapult. (Thirty Years' War-era writers thought the same.)
Despite all of this, there are writers who are talented enough to make guns work in their fantasy settings and even have them achieve a level of coolness equal to medieval weaponry. Perhaps it's understandable why guns aren't seen much in fantasy settings, but it's still nice (if you like guns in your fantasy) when authors manage to do it. After all, there were not only loosely historical The Three Musketeers, but Baron Munchausen himself used a firearm and it didn't made his stories any less of... what, Heroic Fantasy? Of course, it could just be that guns scare children and therefore are never, ever to be in a children's show... even if magic is just used as a stand-in for guns instead. Conversely, assuming that gunpowder must automatically exist once reaching a certain level of advancement is to fall into a logical fallacy; development can happen at different rates in different fields, especially in a world that already has Functional Magic to make long-ranged destructive attacks. This is particularly the case if the functional magic and/or setting results in tactics differing greatly from the setting in which early guns found their first use in real history: firing in volleys using soldiers marching in ranks on battlefields. Guns present their own set of logistical issues in the form of supplies of gunpowder, as well as the cost of munitions (which severely curtailed the number of rounds of ammunition that gunpowder armies could use in training until the second half of the 19th century). Or maybe the author outright despises guns and wants to create a world where they - and whatever other technologies the author may think are ruinous - do not exist for that purpose alone. One historical note apt to be ignored is that the discovery of gunpowder was a major fluke in human history, perhaps the most major one. Unlike many other technologies—like metalworking, stone-cutting, carpentry—as well as inventions like spoons, swords, wheels, bows, etc., which were independently discovered all over the world, gunpowder was discovered exactly once by accident by people who weren't even looking for it: The Chinese. They were in fact searching for an alchemical concoction that would grant immortality and just happened to discover something that explodes, which they turned into rudimentary weapons. After which it spread to the West, where Muslims and Europeans eventually adapted them into guns and cannons. Justifying the Trope There are a number of ways to justify the trope, for those that care to take the time, mostly based on engineering concerns or historical analogy: 1. Literal gun control — The main reason that it took the better part of a millennium for gunpowder to cross from Asia to Europe was that the alchemical 'recipe' was the equivalent of a state secret. In a fantasy culture, even in the absence of that kind of state control of military technology, the people who do all the alchemy tend to be the same people that work with magic, who are easily motivated to keep it a "trade secret" to avoid competition in the realm of fireball-tossing. 2. Missing ingredients — Saltpeter, especially, can be rendered essentially unavailable by basic changes to biology or terrain. For instance, if bats are magical enough to make wandering through caves collecting guano an extreme hazard to life and limb (not a stretch in D&D-based stories) making the stuff isn't worth the pain even if you know how, and it's certainly not common enough to waste on projectile weapons when you've got perfectly serviceable crossbows that have better penetration anyhow. 3. High explosives happened first — If someone worked out how to multiply nitrate glycerine or toluene before working out a low explosive like gunpowder, society may have skipped over to bombs and given alchemical explosives a reputation for being something you don't want anywhere near your face. 4. They exist, but the economies of manufacture and scale aren't good — In the medieval period and, really, the entirety of history up through the US civil war, personal firearms were not quite as long-ranged as crossbows and lacked the penetrating power and reliability, and mostly took over because they were easier to maintain and manufacture, transport, store, and make ammunition for than bolt or arrow weapons. A culture with limited gun-quality steel manufacturing capability, a warlike culture where the average footman trains from childhood, or a culture without a lot of the sieges that necessitated the development of artillery would easily consider guns a curiosity but nothing really worth investing in. Dungeons and Dragons, notably, takes a combination of justification 4 and analogy to real-world medieval firearms: you can purchase them, and they're even simple weapons (you don't need to be a soldier to use them), but they're short-ranged, slow-loading, extremely expensive, prone to failure, and not really any more powerful than their wood-and-iron counterparts, though lucky (critical) shots occur more often.