It's heavily improvised on my keyboard but the trick is to start with a idea (melodic phrase is the formal term) and then develop it, repeat it or contrast it with a different idea.
I must've written over 50+ melodic ideas which are either "melody blocks" or "ending melodies". Once I pick a melody block it goes off from there with improv and then I pick an ending melody. The rest is just connecting the two. Some of them sound great, some just don't. Here's what my favorite ones look like (assuming you know scale degrees and have mastered scales)
1-7-5-3 (over I or IV chord) descending
5-1-2-3 (descending and ascending)
(Btw I think this is an actual approach used by jazz musicians called musical vocabulary. But I don't know much about that yet.)
In webm related I specifically had one phrase and one ending melody in mind, 3-4-3-1-5 and 4-3-1-6-5 (ripped off from nichijou ED). Focusing on just phrases helps make ideas more interesting and endings more satisfying IMO.
Other useful stuff is I'm ear trained to the point where I can write down or play a song just by listening to it once or twice, which depends on your skill on recognizing chord progressions and scale degrees by ear. 8-bit music theory has the best melody tutorials and I still use his antecedent consequent period video to structure my songs.
That's just how it works best for me anyways, some composers don't even know what notes they're using. But my background is analyzing and transcribing piano music to upload to utube for views so the music theory approach feels natural to me.