That's called Lucid dreaming, or dreaming in a state of awareness. You are awake, but your brain thinks you're asleep. It can happen when you lie completely still for about an hour without being able to sleep. Your brain starts checking if you're awake by jolting your legs or arms a little, but if you ignore them, you start dreaming. It's very fun to experiment with, because you can controll your dreams