So I have no background in music theory, only basic knowledge from junior high band, but I've recently started playing trumpet with some friends and I've noticed that when I try to improvise, if I play notes with the same fingering as notes I know are in the scale, the notes I play seem to harmonize well. Is this just happy coincidence, or is there a music theory answer for why this happens? And if there's theory behind it, could someone help me understand it?
There is indeed a reason! The notes you play on a trumpet with a particular fingering come from the harmonic series, which is a series of tones based on the root, or fundamental frequency.
The idea is that the harmonics (also called overtones) are whole-number multiples of the fundamental frequency. If the fundamental frequency of, say, your trumpet, is 100Hz (which is to say, the length of the column of vibrating air in your trumpet matches one whole wavelength at 100Hz), then the first harmonic will be at 200Hz. At that frequency, the trumpet can fit two whole wavelengths. At 300Hz, three whole wavelengths, and so on. These numbers aren't accurate for your trumpet, but the relationship they describe is the same. You can visualize it sorta like so:
Enter Pythagoras, who discovered way back in the BC days that these relationships also govern musical pitches! When you double the fundamental frequency, your note is an octave higher. When you triple the fundamental, your note will be an octave and a fifth higher. When you quadruple it (doubling it twice, mind you) your note will be an octave and a fifth and a fourth higher, or two octaves. This progression continues adding a major third, then a minor third, and so on with diminishing intervals (owing to the fact that the relationship between pitch and frequency is logarithmic.)
So, what happens when you choose scale tones and then jump around with the same fingering is that you're jumping around on that harmonic series. Most trumpet players don't really mess around on fundamentals (I remember, also from junior high band, that I was able to reach waaaay down there and make a kind of awful farting noise by really loosening up the lips) so your first jump will probably be from the first to the second harmonic, which is a fifth. In a major scale, most of the notes (all but the seventh) have a corresponding note exactly a fifth up that is also in that scale, so that first jump leaves you in pretty good shape. The next jump will put you back on the fundamental note, but at a higher octave. All's well there, you're in exactly the right key! The next jump will be a major third, which isn't always going to land you in the same key, but you'll get three out of the seven notes right at least, and that's not too bad. At this point, depending on your level of experience, you may be stretching your embouchure a bit, but you can continue on and find some happy notes in there somewhere.