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:
Position += direction * speed * (float)t.ElapsedGameTime.TotalSeconds;
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:
public override void Update(GameTime t)
{
double msElapsed = t.TotalGameTime.Milliseconds;
mDirection.Y = (float)Math.Sin(msElapsed);
if (mDirection.Y >= 0)
mSpeed.Y = moveSpeed;
else
mSpeed.Y = -moveSpeed;
base.Update(t, mSpeed, mDirection);
}
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!
Answer
You need to move the sprite relative to a center point. To do this, create an offset and alter the position of Y with that offset.
If your Y doesn't move, you can just store your Y:
float center = Position.Y;
float offset = 0; //The offset to add to your Y
float radius = 5; //Whatever you want your radius to be
Then, in your update function, you can offset your Y by a specific amount:
double msElapsed = t.TotalGameTime.Milliseconds;
offset = (float)Math.Sin(msElapsed) * radius;
Position.Y = center + offset;
No comments:
Post a Comment