Adding 2D vector movement with rotation applied
- by Michael Zehnich
I am trying to apply a slight sine wave movement to objects that float around the screen to make them a little more interesting. I would like to apply this to the objects so that they oscillate from side to side, not front to back (so the oscillation does not affect their forward velocity).
After reading various threads and tutorials, I have come to the conclusion that I need to create and add vectors, but I simply cannot come up with a solution that works.
This is where I'm at right now, in the object's update method (updated based on comments):
Vector2 oldPosition = new Vector2(spritePos.X, spritePos.Y);
//note: newPosition is initially set in the constructor to spritePos.x/y
Vector2 direction = newPosition - oldPosition;
Vector2 perpendicular = new Vector2(direction.Y, -direction.X);
perpendicular.Normalize();
sinePosAng += 0.1f;
perpendicular.X += 2.5f * (float)Math.Sin(sinePosAng);
spritePos.X += velocity * (float)Math.Cos(radians);
spritePos.Y += velocity * (float)Math.Sin(radians);
spritePos += perpendicular;
newPosition = spritePos;