Gandalf explains this to Frodo in more detail in the book, in Chapter I.2.
“It was not Gollum, Frodo, but the Ring itself that decided things. The Ring left him.”
“What, just in time to meet Bilbo?” said Frodo. “Wouldn't an Orc have suited it better?”
“The Ring was trying to get back to its master. It had slipped from Isildur's hand and betrayed him; then when a chance came it caught poor Déagol, and he was murdered; and after that Gollum, and it had devoured him. It could make no further use of him: he was too small and mean; and as long as it stayed with him he would never leave his deep pool again. So now, when its master was awake once more and sending out his dark thought from Mirkwood, it abandoned Gollum. Only to be picked up by the most unlikely person imaginable: Bilbo from the Shire!”
Gollum didn't have many visitors. The Ring could have arranged to be picked up by a goblin, but had less incentive until around the time of Bilbo's visit, and (this is speculation on my part, but I didn't invent it) Bilbo was more likely to be effective for the Ring since he was obviously a traveler from afar who was going to travel yet further, unlike the goblins who might have kept the Ring in the caves under the Misty Mountains.
Gandalf suspects that there is more to the Ring's behavior: it may have been determined by Ilúvatar, who would thus have intervened to cause the end of the Third Age, acting in a far more subtle manner than when his reshaping the world marked the end of the Second Age. I don't remember any canonical material dwelling on this.
“Behind that there was something else at work, beyond any design of the Ring-maker. I can put it no plainer than by saying that Bilbo was meant to find the Ring, and not by its maker.”