If you'd like to be able to play piano by ear, you need to train your fingers to play what they "hear."
No one thinks it's all that amazing to be able to hear a tune and sing it back accurately - it's just what the muscles that control your voice are trained to do. Over time, your fingers will gain enough experience to do this as well.
The first step is to be able to follow the contour of a melody up or down. As you are listening to a recording or singing a song, allow the fingers of your right hand to move with it on a table top or steering wheel (hat tip to Laura Marlow for sharing this technique with me almost twenty years ago). Up is to the right, and down is to the left. For a three-note melody moving up, you might "play" thumb, index finger, middle finger in succession, and for a melody moving down you would reverse it (middle, index, thumb).
As you refine your skills, you'll start to be able to sense when a melody is making a larger jump versus a scalewise step, and reflect this with your fingers.
Of course, you'll want to put in some time on the piano. Start with very simple melodies or scale patterns at first, such as "Twinkle Twinkle Little Star." You'll bring a natural feedback mechanism into play: Wrong notes will annoy you, and you'll work to avoid them. That doesn't mean you'll never make the same mistake twice, but as the days go by you will find yourself staying on the straight and narrow more and more.
A grasp of music theory, the grammar of music, is extremely helpful when playing by ear. Music theory helps you to see the patterns underlying the music so that you can assimilate ideas quickly and predict what's coming next.
One piece of counter-intuitive advice: Learn to read music. Being able to read a piece of music smoothly from a written score expands the musical vocabulary you have in your fingers. You might also notice that an understanding of written music improves your ability to visualize the melodic contour you're hearing, even when there's no printed score involved.
Playing by ear "on the fly" once seemed to me like a magical, God-given gift - until, as an adult, I learned to do it. I believe that anyone can. Hopefully, these tips will encourage you to give it a try regardless of your level of experience.