I'm working on a 2d game and am looking to make a sprite move horizontally across the screen in XNA while oscillating vertically (basically I want the movement to look like a sin wave). Currently for movement I'm using two vectors, one for speed and one for direction. My update function for sprites just contains this:

How could I utilize this setup to create the desired movement? I'm assuming I'd call Math.Sin or Math.Cos, but I'm unsure of where to start to make this sort of thing happened. My attempt looked like this:

moveSpeed is just some constant positive integer. With this, the sprite simply just continuously moves downward until it's off screen. Can anyone give me some info on what I'm doing wrong here? I've never tried something like this so if I'm doing things completely wrong, let me know!

This works great! Thanks a lot. It looks a little crazy right now because the frame rate is so fast, but I can work on that to make it smooth.
–
Nick Van HoogenstynMar 2 '11 at 4:34

1

You should not use msElapsed as the input to the sin function class. Instead, use an angle that you increment and then multiply by msElapsed time => Math.sin(angle*msElapsed), that way no matter the frame rate the oscillation will be smooth.
–
dotminicMar 2 '11 at 5:33

Would I just increment the angle by 1 every time the update function is called? When I try that, it just stays jittery. And is the angle just an integer?
–
Nick Van HoogenstynMar 2 '11 at 6:38

The angle would be a float and the bigger the incrementation, the faster the movement. For example, this increments an angle I use to rotate a camera arround an object in a 3D world: this->_phi += .34f * dt; where dt is the same as msElapsed.
–
dotminicMar 2 '11 at 14:16

Essentially, what the sine function does is return a float point value in range [-1,1] based on the input angle (in radians). You can then scale that result by the radius, in the example, I scale the value by 5 given me a value in the range [-5, 5], and then all you need to do is add that value to the Y position you want the sprite to oscillate around.

You can also think of the "speed" variable as the frequency of the wave in this line:

angle += speed * elapsedTime;

The higher the speed the faster the oscillation will be. Note however that this isn't physically accurate, to make waves and have control of amplitude, frequency and other parameters is a little more "complicated".