In my experience, unfortunately, writing melodies is one of the most "magical" parts of writing music. Some melodies just sound great, some just don't. There are, however, a few things to keep in mind that can help you deliberately write a melody for a particular emotion or style and help you understand why a particular melody sounds good.
Intervallic and Stepwise Motion:
Some melodies have large jumps in-between consecutive notes, and others move up or down consecutive notes in a scale. The former usually sounds more grand, especially with slow rhythms, and the latter, smoother.
Rising and Falling Motion:
Whether the notes in a melody generally get higher, get lower, or stay in the same range can have a big effect on the melody's emotion.
The melody you pick for a rhythm makes a huge difference. Is it syncopated or straight? Fast or slow? Complex or simple? Does it use distinctive tricks like hemiola or tuplets? What beats does it start and end on?
In my experience, the instrument playing a melody makes a big difference. In the EDM track The End, the main melody is played by a number of bold, powerful synths, giving the melody a driving emotion. Then, at the end of the song, a lone acoustic guitar plays the same melody, which suddenly becomes very sad.
Of course, whether a melody is written in a major or minor key makes a big difference.
And the list can go on forever: tonal center, articulation, etc. The important thing isn't that every melody can be broken apart like this. Instead, you can pick out a few qualities you know you would like a melody to have based on which emotion you want to portray.
For example, perhaps you need to write the leitmotif for the bad guy. It's probably going to be in a minor key, because he's so evil. Likewise, it might be played in a lower register on an instrument like a bassoon, not on a lighter instrument like a flute. And although the motif will be centered around a particular key, it might use a lot of chromatic, dissonant notes. You can play with all the other attributes of a melody while you try to figure out what you're ultimately going to go with, but starting with a plan like this makes it easier to begin writing a melody.