Impulses from the brain cause erections during the dreaming phase of sleep, called the REM phase. It doesn't matter if you're having a hot sex dream or a zombie apocalypse nightmare -- your penis gets hard during that period of the sleep cycle.