There are many elements that goes into writing a melody. The basis of any melody starts with the scale.
Without going into a lot technical explanation, the reason the notes in a scale sound right is because they are a series of “stacked” fifth intervals. Next to an octave interval the most pleasant sounding interval is the fifth. Study the circle of fifth and you will discover how the major scale is constructed.
Once the major scale is constructed, modes scales can be made by moving the tonic (starting note) to a different note on the scale. In doing this the emotional feel of the scale will change. The major scale in the key of C consists of these notes CDEFGABC. By moving the tonic to D the Dorian scale is created here are those notes DEFGABCD. Here is more information on Understanding Scale Modes
When composing a melody start with a small musical phase called a motif. The motive is just a musical idea. Composers will take that motif and morph it using various composition devices like, repeating, series, invert, retrograde. Doing this will create a musical phase. The classic example is Beethoven’s Fifth Symphony. It starts with that four note motive and the composer morphs it into many different configurations.
A good melody will consist of a call and response or question and answer. One musical phase will be followed by another that contrast and answers the phase.
A melody line will 80% of the time follow a step wise note to note pattern. Other times there will be a leap in neighboring notes (an interval greater than a third). It is the leap that will create interest and memorability into the melody. However, to reinforce its effectiveness it needs to be used sparingly.
Many melody lines will follow an arch pattern. That goes like this. Starting note goes up, then reaches the highest note, followed by a descending notes.
To learn how to write a melody it is a good practice to study melody lines that you like and figure out what the composer did. Find the main motif. what are the musical phases?
There is definitely a method that goes into composing a beautiful melody. There is many other