I have two bikes that when I pedal (yes I am pedaling in the correct direction) the gears turn freely, but the wheels don't. One of them I was riding and it felt like it had shifted while I was standing on it, and the next thing I knew I was walking home. The other one my friend was riding at the time.
Inside your rear wheel is what is called a free hub. It has a ratcheting mechanism that allows you to pedal backwards while conversely engaging when you pedal forward so to transfer pedal force to the wheel. I've been stuck on a trail more than once due to a free hub failing to engage.
Unfortunately your free hub is generally not servicable. Depending on the quality of the wheel, it is sometimes cheaper to just buy a new wheel vs paying someone to re lace your existing one.
Other than a broken chain, which would be obvious, I don't know of anything else that would cause your wheel not to move when you pedal forward.
There's this video, which shows how to clean a freewheel without disassembling its innards. (What @daniel-r-hicks said reminded me of this.) It assumes you can get it off the bike to work on it.
This video shows how to do the same thing for a freehub (as opposed to freewheel).
I can't tell if:
- yours is a freewheel or freehub, I don't think you've said
- the problem is your chain coming off the gears or it's staying on but not turning the wheel
so it's hard to know if this video answers your question.
Difference between freewheel and freehub -
What's in a freewheel (how does it work) -